3 回答
TA贡献1784条经验 获得超9个赞
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()
这就是你想要的。它完全按照你说的那样工作。
TA贡献1845条经验 获得超8个赞
只需使用index // group_sizeas 键即可满足您的需求:
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()
TA贡献1828条经验 获得超3个赞
不是最直接的方法,但至少它有效:
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
输出:
1.James
1.Heather
1.Daniel
2.Peter
2.Frank
2.Sam
3.Jeff
您可以将 print 函数中的内容保存到 txt 文件中:
with open('Groups.txt', 'w') as g:
g.write('\n'.join([f'{i}.{j}' for j,i in zip(string_list,numbers_list)]))
添加回答
举报