2014-12-27 153 views

回答

2
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) 

输出:

+27

我downvoted蟒蛇的阴影,因为这并不能解释为什么原来的代码没有工作或OP的理解错误在哪里。 – SethMMorton

1

它应该是:

for s in my_list:  # here s is element of list not index of list 
    t = (s, 1) 
    map_list.append(t) 

我想你想:

for i,s in enumerate(my_list): # here i is the index and s is the respective element 
    t = (s, i) 
    map_list.append(t) 

enumerate给指数和元素

注意:使用list作为变量名是不好的做法。其内置功能

5

请勿使用名称list作为列表。下面我使用了mylist

for s in mylist: 
    t = (mylist[s], 1) 

for s in mylist:分配的mylist元件ss即发生在第二次迭代中在第一次迭代的值“ABC”和“DEF”。因此,s不能用作mylist[s]中的索引。

相反,简单地做:

for s in lists: 
    t = (s, 1) 
    map_list.append(t) 
print map_list 
#[('abc', 1), ('def', 1)] 
11

当你遍历一个列表,循环变量接收实际的列表元素,而不是他们的索引。因此,在您的示例s是一个字符串(首先abc,然后def)。

它看起来像你想做什么本质上是这样的:

orig_list = ['abc', 'def'] 
map_list = [(el, 1) for el in orig_list] 

这是使用所谓的list comprehension一个Python构造。

0

for s in list将产生列表中的项目而不是它们的索引。所以s将为'abc'第一个循环,然后 'def''abc'只能是字典的关键字,而不是列表索引。

t一致通过索引获取项目在Python中是多余的。

相关问题