python 如何在python列表中获取某个索引的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1943824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value on a certain index, in a python list?
提问by Fahim Akhter
I have a list which looks something like this
我有一个看起来像这样的列表
List = [q1,a1,q2,a2,q3,a3]
I need the final code to be something like this
我需要最终的代码是这样的
dictionary = {q1:a1,q2:a2,q3:a3}
if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it?
如果我只能在某个索引处获取值,例如 List[0] 我可以完成此操作,有什么方法可以获得它吗?
回答by zzzeek
Python dictionaries can be constructed using the dict
class, given an iterable containing tuples. We can use this in conjunction with the range
builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict
, such that the values organize themselves into key/value pairs in the final result:
dict
给定包含元组的可迭代对象,可以使用该类构造 Python 字典。我们可以将它与range
内置函数结合使用来生成一个元组集合,如 (every-odd-item, every-even-item),并将其传递给dict
,以便值在最终组织成键/值对结果:
dictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)])
回答by sth
Using extended slice notation:
使用扩展切片符号:
dictionary = dict(zip(List[0::2], List[1::2]))
回答by Peter Hansen
The range-based answer is simpler, but there's another approach possible using the itertools package:
基于范围的答案更简单,但使用 itertools 包还有另一种可能的方法:
from itertools import izip
dictionary = dict(izip(*[iter(List)] * 2))
Breaking this down (edit:tested this time):
打破这个(编辑:这次测试):
# Create instance of iterator wrapped around List
# which will consume items one at a time when called.
iter(List)
# Put reference to iterator into list and duplicate it so
# there are two references to the *same* iterator.
[iter(List)] * 2
# Pass each item in the list as a separate argument to the
# izip() function. This uses the special * syntax that takes
# a sequence and spreads it across a number of positional arguments.
izip(* [iter(List)] * 2)
# Use regular dict() constructor, same as in the answer by zzzeeek
dict(izip(* [iter(List)] * 2))
Edit: much thanks to Chris Lutz' sharp eyes for the double correction.
编辑:非常感谢 Chris Lutz 对双重更正的敏锐眼光。
回答by inspectorG4dget
d = {}
for i in range(0, len(List), 2):
d[List[i]] = List[i+1]
回答by Chris Lutz
You've mentioned in the comments that you have duplicate entries. We can work with this. Take your favorite method of generating the list of tuples, and expand it into a for
loop:
您在评论中提到您有重复的条目。我们可以解决这个问题。使用您最喜欢的生成元组列表的方法,并将其扩展为一个for
循环:
from itertools import izip
dictionary = {}
for k, v in izip(List[::2], List[1::2]):
if k not in dictionary:
dictionary[k] = set()
dictionary[k].add(v)
Or we could use collections.defaultdict
so we don't have to check if a key is already initialized:
或者我们可以使用collections.defaultdict
这样我们就不必检查密钥是否已经初始化:
from itertools import izip
from collections import defaultdict
dictionary = defaultdict(set)
for k, v in izip(List[::2], List[1::2]):
dictionary[k].add(v)
We'll end with a dictionary where all the keys are sets, and the sets contain the values. This still may not be appropriate, because sets, like dictionaries, cannot hold duplicates, so if you need a single key to hold two of the same value, you'll need to change it to a tuple or a list. But this should get you started.
我们将以一个字典结束,其中所有的键都是集合,集合包含值。这仍然可能不合适,因为集合和字典一样不能保存重复项,所以如果您需要一个键来保存两个相同的值,您需要将其更改为元组或列表。但这应该让你开始。