[英]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 但是我正在尝试从for循环打印的数字中创建一个新列表。这是我输入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]? 我怎样才能将0 2 6变成[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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.