0

I have a list (list.txt) which consists of names like so: James Heather Daniel Peter

The list goes on up to 100 people, my goal is to number the first 3 (x) '1.' the next 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.

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

1.Heather

1.Daniel

1.Peter

2.Frank

2.Sam

2.Jeff

...etc

Josef
  • 15
  • 2
  • Take a look at this question: https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks - it's not a 100% dupe of this but it should steer you in the right direction. – Peter DeGlopper Sep 23 '19 at 18:49

4 Answers4

1
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.

Jiraiya
  • 101
  • 1
  • 9
1

Simply using index // group_size as the key gives what you want:

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()
GZ0
  • 4,055
  • 1
  • 10
  • 21
0

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:

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:

with open('Groups.txt', 'w') as g:
    g.write('\n'.join([f'{i}.{j}' for j,i in zip(string_list,numbers_list)]))
Juan C
  • 5,846
  • 2
  • 17
  • 51
0
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

h43ckm43ck
  • 74
  • 6