Python :将整数转换为计数(即 3 --> 1,2,3)
Python : Convert Integers into a Count (i.e. 3 --> 1,2,3)
这可能比解释我的问题所需的信息更多,但我正在尝试将 2 个脚本(我为其他用途编写的)组合在一起以执行以下操作。
目标字符串 (input_file) 4FOO
2BAR
结果 (output_file) 1FOO
2FOO
3FOO
4FOO
1BAR
2BAR
我的第一个脚本找到了模式并复制到 file_2
pattern = "\d[A-Za-z]{3}"
matches = re.findall(pattern, input_file.read())
f1.write('\n'.join(matches))
我的第二个脚本打开 output_file 并使用 re.sub,使用捕获组和反向引用替换和更改目标字符串。但是我被困在这里如何将 3
变成 1
2
3
.
有什么想法吗?
假设您的数字在 1 到 9 之间,没有正则表达式,您可以使用带有 f 字符串的列表理解 (Python 3.6+):
L = ['4FOO', '2BAR']
res = [f'{j}{i[1:]}' for i in L for j in range(1, int(i[0])+1)]
['1FOO', '2FOO', '3FOO', '4FOO', '1BAR', '2BAR']
读取和写入 CSV 文件在别处介绍:read, write。
更一般化,要计算大于 9 的数字,您可以使用 itertools.groupby
:
from itertools import groupby
L = ['4FOO', '10BAR']
def make_var(x, int_flag):
return int(''.join(x)) if int_flag else ''.join(x)
vals = ((make_var(b, a) for a, b in groupby(i, str.isdigit)) for i in L)
res = [f'{j}{k}' for num, k in vals for j in range(1, num+1)]
print(res)
['1FOO', '2FOO', '3FOO', '4FOO', '1BAR', '2BAR', '3BAR', '4BAR',
'5BAR', '6BAR', '7BAR', '8BAR', '9BAR', '10BAR']
这个简单的例子不需要使用正则表达式,但如果你想使用 re
,这里是例子(注意:你的模式有小错误,应该是 A-Z
, 不是 A-A
):
text_input = '4FOO 2BAR'
import re
matches = re.findall(r"(\d)([A-Za-z]{3})", text_input)
for (count, what) in matches:
for i in range(1, int(count)+1):
print(f'{i}{what}', end=' ')
print()
打印:
1FOO 2FOO 3FOO 4FOO 1BAR 2BAR
注意:如果要支持多位数字,可以使用(\d+)
——注意+
符号。
这可能比解释我的问题所需的信息更多,但我正在尝试将 2 个脚本(我为其他用途编写的)组合在一起以执行以下操作。
目标字符串 (input_file) 4FOO
2BAR
结果 (output_file) 1FOO
2FOO
3FOO
4FOO
1BAR
2BAR
我的第一个脚本找到了模式并复制到 file_2
pattern = "\d[A-Za-z]{3}"
matches = re.findall(pattern, input_file.read())
f1.write('\n'.join(matches))
我的第二个脚本打开 output_file 并使用 re.sub,使用捕获组和反向引用替换和更改目标字符串。但是我被困在这里如何将 3
变成 1
2
3
.
有什么想法吗?
假设您的数字在 1 到 9 之间,没有正则表达式,您可以使用带有 f 字符串的列表理解 (Python 3.6+):
L = ['4FOO', '2BAR']
res = [f'{j}{i[1:]}' for i in L for j in range(1, int(i[0])+1)]
['1FOO', '2FOO', '3FOO', '4FOO', '1BAR', '2BAR']
读取和写入 CSV 文件在别处介绍:read, write。
更一般化,要计算大于 9 的数字,您可以使用 itertools.groupby
:
from itertools import groupby
L = ['4FOO', '10BAR']
def make_var(x, int_flag):
return int(''.join(x)) if int_flag else ''.join(x)
vals = ((make_var(b, a) for a, b in groupby(i, str.isdigit)) for i in L)
res = [f'{j}{k}' for num, k in vals for j in range(1, num+1)]
print(res)
['1FOO', '2FOO', '3FOO', '4FOO', '1BAR', '2BAR', '3BAR', '4BAR',
'5BAR', '6BAR', '7BAR', '8BAR', '9BAR', '10BAR']
这个简单的例子不需要使用正则表达式,但如果你想使用 re
,这里是例子(注意:你的模式有小错误,应该是 A-Z
, 不是 A-A
):
text_input = '4FOO 2BAR'
import re
matches = re.findall(r"(\d)([A-Za-z]{3})", text_input)
for (count, what) in matches:
for i in range(1, int(count)+1):
print(f'{i}{what}', end=' ')
print()
打印:
1FOO 2FOO 3FOO 4FOO 1BAR 2BAR
注意:如果要支持多位数字,可以使用(\d+)
——注意+
符号。