简体   繁体   中英

Nested Loop for printing out different strings (Python)

I would like to print the right strings from a list I have, while looping through another list I have.

My two lists look like this:

overview_list = ['1','2','3']
my_list = ['name1', 'year1', 'date1', 'numbre1', 
'name2', 'year2', 'date2', 'numbre2',
'name3','year3','date3', 'numbre3']

I would like to loop through the overview_list and for every string I would like to print() the corresponding strings from my_list .

These are:

for '1' from overview_list it sould be printed: 'name1', 'year1', 'date1', 'numbre1'

for '2' from overview_list it should be printed: 'name2', 'year2', 'date2', 'numbre2'

and so on....

I think this could be done with a nested loop, but I am still a beginner in Python and do not know how. Thank you very much for your help!

try this, you don't need nested loop's instead using range(start, stop, step) + splicing

over_view = 3

for i in range(0, len(my_list), over_view + 1):
    print(", ".join(my_list[i: i + over_view + 1]))

name1, year1, date1, numbre1
name2, year2, date2, numbre2
name3, year3, date3, numbre3

If you would like to print every string in a different row:

overview_list = ['1','2','3']
my_list = ['name1', 'year1', 'date1', 'numbre1', 
'name2', 'year2', 'date2', 'numbre2',
'name3','year3','date3', 'numbre3']

for number in overview_list:
    for elem in my_list:
        if number in elem:
            print(elem)

Another option if you would like to print together all the strings that relate to one number:

overview_list = ['1','2','3']
my_list = ['name1', 'year1', 'date1', 'numbre1', 
'name2', 'year2', 'date2', 'numbre2',
'name3','year3','date3', 'numbre3']

for number in overview_list:
    for elem in my_list:
        if number in elem:
            print(elem, end=" ")
    print()

BTW you wrote numbre instead of number in 'my_list'

An addition after your comment: In order to use the ordinal number of any string in overview_list - try this:

overview_list = ['x','y','z']
my_list = ['name1', 'year1', 'date1', 'numbre1', 
'name2', 'year2', 'date2', 'numbre2',
'name3','year3','date3', 'numbre3']

for index, item in enumerate(overview_list, 1):
    for elem in my_list:
        if str(index) in elem:
            print(elem, end=" ")
    print() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM