[英]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.