[英]How do you number a text file but also repeat each number x amount of times before counting up again?
I have a list (list.txt) which consists of names like so: James Heather Daniel Peter我有一个列表(list.txt),其中包含如下名称:James Heather Daniel Peter
The list goes on up to 100 people, my goal is to number the first 3 (x) '1.'这份名单最多有 100 人,我的目标是给前 3 (x) 个“1”编号。 the next 3 (x) '2.'
接下来的 3 (x) '2'。 and so on.
等等。
I have managed to number each person but the number increases as expected with no repetition.我设法给每个人编号,但数字按预期增加,没有重复。
Preferably I want to print the list into Groups.txt to keep the original list untouched so I can later change the size (k) of the groups.最好我想将列表打印到 Groups.txt 中以保持原始列表不变,以便我以后可以更改组的大小 (k)。
I have tried to somehow implement the following codes into the below:我试图以某种方式将以下代码实现到以下代码中:
res = list(itertools.chain.from_iterable(itertools.repeat(y, 3) for y in c))
or或者
res = [ele for ele in c for i in range(k)]
But it did not work.但它没有用。
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()
Here again what I wish to have as an output: 1.James这里又是我希望拥有的 output:1.James
1.Heather 1.希瑟
1.Daniel 1.丹尼尔
1.Peter 1.彼得
2.Frank 2.弗兰克
2.Sam 2.山姆
2.Jeff 2.杰夫
...etc ...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()
Here is what you want.这就是你想要的。 It works exactly as you said.
它完全按照你说的那样工作。
Simply using index // group_size
as the key gives what you want:只需使用
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()
Not the most straightforward way, but at least it works:不是最直接的方法,但至少它有效:
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: Output:
1.James
1.Heather
1.Daniel
2.Peter
2.Frank
2.Sam
3.Jeff
You can save what's inside the print function into your txt file:您可以将打印 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
https://docs.python.org/3.7/library/functions.html#divmod https://docs.python.org/3.7/library/functions.html#divmod
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.