I am given the following list
mylist=[25,42,58,31,20,11,42]
which I separated them into a new list
newlist=[[25,42,58,31],[20,11,42]]
Then I need to print it as follow. How do I code it in a way where all the index will be printed?
First sequence is : 0,1,2,3
Second sequence is : 4,5,6
CodePudding user response:
The following is one implementation using itertools.count
:
import itertools
newlist=[[25,42,58,31],[20,11,42]]
cnt = itertools.count()
for i, sublst in enumerate(newlist):
print(f"Sequence {i}:", [next(cnt) for _ in sublst])
# Sequence 0: [0, 1, 2, 3]
# Sequence 1: [4, 5, 6]
I personally find this method concise.
CodePudding user response:
Assuming this only depends of newlist
(i.e newlist
is a valid split of mylist
):
newlist=[[25,42,58,31],[20,11,42]]
start = 0
for i, l in enumerate(newlist):
seq = range(start, start len(l))
start = len (l)
print(f'sequence {i} is: {",".join(map(str,seq))}')
Output:
sequence 0 is: 0,1,2,3
sequence 1 is: 4,5,6
CodePudding user response:
What you have here is a list of lists that you could interate through and count the results.
addition = 0
for idx, item in enumerate(newlist):
if idx != 0:
addition = len(newlist[idx-1])
print(f"Sequence of item {idx 1}: {[i addition for i in range(len(item))]}"
CodePudding user response:
You can use the inflect
package to convert 1, 2, 3 to 1st, 2nd, 3rd...
Quick prototype:
import inflect
p = inflect.engine()
for i in range(len(newlist)):
print(f"{p.ordinal(i)} sequence is {','. join(map(str , seq))}}")