简体   繁体   English

双重错误,python

[英]Some error in double for, python

I have some variables like this: 我有一些这样的变量:

letters = ["a","b","c","d"]
num = ["1","2","3","4"]
names = ["Paul","John"]

for i in letters:
    for j in names:
          output= names[j] + letters[i] + num[i]
          print output

I would like to get some kind of output like this: 我想要这样的输出:

output print:
"Paul a 1" 
"John a 1" 
"Paul b 2" 
"John b 2" 
"Paul c 3"
"John c 3" 
"Paul d 4" 
"John d 4" 

But somehow I cant find the right way to get this combination. 但是我不知何故找不到正确的方法来获得这种结合。 Any ideas where is the error? 任何想法错误在哪里?

You should do it as this instead: 您应该这样做:

letters = ["a", "b", "c", "d"]
num = ["1", "2", "3", "4"]
names = ["Paul", "John"]

for a, i in enumerate(letters):
    for j in names:
          print j, i, num[a]

The problem you are facing is that i , and j are elements of the list not indices. 您面临的问题是ij是列表的元素而不是索引。 If you want to get the index and element from a list, you use enumerate() . 如果要从列表中获取索引和元素,请使用enumerate()

Example

>>> a = ['a', 'b', 'c']

>>> for i, item in enumerate(a):
...     print i, item
...
0 a
1 b
2 c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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