[英]How do you number a text file but also repeat each number x amount of times before counting up again?
我有一个列表(list.txt),其中包含如下名称:James Heather Daniel Peter
这份名单最多有 100 人,我的目标是给前 3 (x) 个“1”编号。 接下来的 3 (x) '2'。 等等。
我设法给每个人编号,但数字按预期增加,没有重复。
最好我想将列表打印到 Groups.txt 中以保持原始列表不变,以便我以后可以更改组的大小 (k)。
我试图以某种方式将以下代码实现到以下代码中:
res = list(itertools.chain.from_iterable(itertools.repeat(y, 3) for y in c))
或者
res = [ele for ele in c for i in range(k)]
但它没有用。
f = open('list.txt', 'w')
c = open('Groups.txt')
x = 3
for index, value in enumerate(c, 1):
f.write("{}.{}".format(index, value))
f.close()
这里又是我希望拥有的 output:1.James
1.希瑟
1.丹尼尔
1.彼得
2.弗兰克
2.山姆
2.杰夫
...ETC
f = open('list.txt', 'w')
c = open('test.txt')
lines = c.readlines()
counter = 0
for i in range(len(lines)):
if i%3 == 0:
counter+=1
f.write("{}.{}".format(counter, lines[i]))
f.close()
这就是你想要的。 它完全按照你说的那样工作。
只需使用index // group_size
作为键即可提供您想要的:
f = open('list.txt', 'w')
c = open('Groups.txt')
group_size = 3
for index, value in enumerate(f, group_size):
f.write("{}.{}".format(index // group_size, value))
f.close()
不是最直接的方法,但至少它有效:
string = 'James Heather Daniel Peter Frank Sam Jeff'
string_list = string.split() #Turn string into list
k = 3 #Group size
needed_numbers =range(int(np.ceil(len(string_list)/k))) #Divide len by k and round upwards
numbers_list = [y+1 for x in needed_numbers for y in (x,)*k] #Get list of numbers
print('\n'.join([f'{i}.{j}' for j,i in zip(string_list,numbers_list)])) #Join both
Output:
1.James
1.Heather
1.Daniel
2.Peter
2.Frank
2.Sam
3.Jeff
您可以将打印 function 中的内容保存到您的 txt 文件中:
with open('Groups.txt', 'w') as g:
g.write('\n'.join([f'{i}.{j}' for j,i in zip(string_list,numbers_list)]))
index = 0
group = 1
for _ in range(0, 10):
index += 1
print(f"{group}:{index}")
if index % 3 == 0:
group += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.