简体   繁体   中英

Create list from for loop

this is my code so far

print("L = ",[4,10,4,2,9,5,4])

Startlist = [4,10,4,2,9,5,4]
usrinput = int(input("Enter an element to search for in the list: "))
for i in [i for i,x in enumerate(Startlist) if x == usrinput]:
    print(i)

I'm trying to however make a new list from the for loops printed numbers.This is the sample run i got by entering 4

L =  [4, 10, 4, 2, 9, 5, 4]
Enter an element to search for in the list: 4
0
2
6

how could i turn the 0 2 6 into [0,2,6]?

Thanks for any responses

只需打印列表理解:

print([i for i,x in enumerate(Startlist) if x == usrinput])

You already made the list! The heavy lifting in your code is in the temporary array you created and iterated over.

 newlist = [i for i,x in enumerate(Startlist) if x == usrinput]

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