例如,如果我有两个列表:组合两个列表成为一个辞典蟒蛇
listA = [1, 2, 3, 4, 5]
listB = [red, blue, orange, black, grey]
我试图找出如何在两列显示两个参数列表中的元素, 分配1: red, 2: blue...
等。
这必须在不使用内置zip
函数的情况下完成。
例如,如果我有两个列表:组合两个列表成为一个辞典蟒蛇
listA = [1, 2, 3, 4, 5]
listB = [red, blue, orange, black, grey]
我试图找出如何在两列显示两个参数列表中的元素, 分配1: red, 2: blue...
等。
这必须在不使用内置zip
函数的情况下完成。
>>> listA = [1, 2, 3, 4, 5]
>>> listB = ["red", "blue", "orange", "black", "grey"]
>>> dict(zip(listA, listB))
{1: 'red', 2: 'blue', 3: 'orange', 4: 'black', 5: 'grey'}
不幸的是,我的老师不希望我们使用'拉链',因为我们没有超过它。教师为 – 2014-10-09 02:24:22
-1。不鼓励学生阅读,不是教学。 – 2014-10-09 03:33:37
你为什么要转换成'dict'?不能保证'dict'打印的顺序。 – 2014-10-09 03:40:39
如果您不能使用zip,请执行for循环。
d = {} #Dictionary
listA = [1, 2, 3, 4, 5]
listB = ["red", "blue", "orange", "black", "grey"]
for index in range(min(len(listA),len(listB))):
# for index number in the length of smallest list
d[listA[index]] = listB[index]
# add the value of listA at that place to the dictionary with value of listB
print (d) #Not sure of your Python version, so I've put d in parentheses
我怀疑你的老师要你写类似
for i in range(len(listA)):
print listA[i], listB[i]
然而,这是在Python所厌恶的。
这里是不使用zip
>>> listA = [1, 2, 3, 4, 5]
>>> listB = ["red", "blue", "orange", "black", "grey"]
>>>
>>> b_iter = iter(listB)
>>>
>>> for item in listA:
... print item, next(b_iter)
...
1 red
2 blue
3 orange
4 black
5 grey
方法之一,不过zip
是自然的方式来解决这个问题,和你的老师应该教你这样认为
通常,zip
是解决您的问题的最佳途径。但由于这是一项家庭作业,而且您的老师不允许您使用zip
,我认为您可以从此页面采取任何解决方案。
我提供了一个使用lambda函数的版本。请注意,如果两个列表的长度不相同,则将在相应位置打印None
。
>>> list_a = [1, 2, 3, 4, 5]
>>> list_b = ["red", "blue", "orange", "black", "grey"]
>>> for a,b in map(lambda a,b : (a,b), list_a, list_b):
... print a,b
...
1 red
2 blue
3 orange
4 black
5 grey
特殊教师版:
list_a = [1, 2, 3, 4, 5]
list_b = ["red", "blue", "orange", "black", "grey"]
for i in range(min(len(list_a), len(list_b))):
print list_a[i], list_b[i]
检查出[拉链](https://docs.python.org/2/library/functions.html#zip)函数 – bruchowski 2014-10-09 02:15:12
@ stanleyxu2005,做我想念'dict'吗?为什么你和其他两个答案在这里使用'dict'? – 2014-10-09 03:45:23
@gnibbler哦,你是对的。他的代表'1:红色,2:蓝色'误导我创造一个字典。他也希望不用'zip'解决问题。这似乎是一种家庭作业的问题... – stanleyxu2005 2014-10-09 04:17:11