list1 = ['abc', 'def']
list2=[]
for t in list1:
for h in t:
list2.append(h)
map_list = []
for x,y in enumerate(list2):
map_list.append(x)
print (map_list)
输出:
>>>
[0, 1, 2, 3, 4, 5]
>>>
这正是你想要的。
If you dont want to reach each element then:
list1 = ['abc', 'def']
map_list=[]
for x,y in enumerate(list1):
map_list.append(x)
print (map_list)
不要对列表使用名称
list
。我使用了下面的mylist
。for s in mylist:
将mylist
的元素分配给s
,即s
在第一次迭代中使用值“abc”,在第二次迭代中使用值“def”。因此,s
不能用作mylist[s]
中的索引。相反,只要做:
当您在列表上迭代时,循环变量接收实际的列表元素,而不是它们的索引。因此,在您的示例中,
s
是一个字符串(首先是abc
,然后是def
)。看起来你要做的基本上是:
这是使用一个名为list comprehension的Python构造。
输出:
这正是你想要的。
输出:
相关问题 更多 >
编程相关推荐