python 在python中填充一个列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/696874/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:40:20  来源:igfitidea点击:

Populate a list in python

pythonlisttuples

提问by disc0dancer

I have a series of Python tuples representing coordinates:

我有一系列表示坐标的 Python 元组:

tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]

I want to create the following list:

我想创建以下列表:

l = []
for t in tuples:
  l[ t[0] ][ t[1] ] = something

I get an IndexError: list index out of range.

我得到一个 IndexError: list index out of range。

My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.

我的背景是 PHP,我希望在 Python 中您可以创建以索引 > 0 开头的列表,即创建空白然后填充它们,但似乎您不能。

The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. Update: I now know they can - see the accepted solution.

这个想法是在之后对列表进行排序。我知道我可以用字典来做到这一点,但据我所知,字典不能按键排序。 更新:我现在知道他们可以 - 查看已接受的解决方案。

Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)

编辑:我想要做的是创建一个二维数组,该数组将表示用元组坐标描述的矩阵,然后按顺序迭代它。如果我使用字典,我不能保证对键进行迭代 -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2 ) (2,0) (2,1) (2,2)

Can anyone help?

任何人都可以帮忙吗?

采纳答案by Rodrigo

What do you mean exactly by "but as far as I know dictionaries cannot be sorted by keys"?

“但据我所知,字典不能按键排序”是什么意思?

While this is not strictly the same as a "sorted dictionary", you caneasily turn a dictionary into a list, sorted by the key, which seems to be what you're after:

虽然这与“排序字典”并不严格相同,但您可以轻松地将字典转换为按键排序的列表,这似乎是您所追求的:

>>> tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
>>> l = {}
>>> for t in tuples:
...    l[t] = "something"
>>> sorted(l) # equivalent to sorted(l.keys())
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 1)]
>>> sorted(l.items()) # make a list of (key, value) tuples, and sort by key
[((0, 0), 'something'), ((0, 1), 'something'), ((1, 0), 'something'), ((1, 1), 'something'), ((2, 1), 'something')]    

(I turned somethinginto the string "something" just to make the code work)

(我变成something了字符串“something”只是为了让代码工作)

To make use of this for your case however (if I understand it correctly, that is), you would still need to fill the dictionary with None values or something for every "empty" coordinate tuple)

但是,要在您的情况下使用它(如果我理解正确,那就是),您仍然需要使用 None 值或每个“空”坐标元组的内容填充字典)

回答by Rorick

No, you cannot create list with gaps. But you can create a dictionary with tuple keys:

不,您不能创建有间隙的列表。但是您可以使用元组键创建字典:

tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
l = {}
for t in tuples:
    l[t] = something

Update:Try using NumPy, it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on the site (3.4.3 Flat Iterator indexing): "As mentioned previously, X.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest". Looks like what you need.

更新:尝试使用NumPy,它提供了对矩阵和数组的广泛操作。引用网站上可用的 NumPy 上的免费 pfd(3.4.3 Flat Iterator indexing):“如前所述,X.flat 返回一个迭代器,它将迭代整个数组(在 C 连续样式中,最后一个索引变化最快”. 看起来像你需要的。

回答by Rorick

You should look at dicts for something like that.

你应该看看类似的东西。

for t in tuples:
  if not l.has_key(t[0]):
    l[t[0]] = {}
  l[t[0]][t[1]] = something

Iterating over the dict is a bit different than iterating over a list, though. You'll have the keys(), values() and items() functions to help with that.

不过,遍历 dict 与遍历列表有点不同。您将拥有 keys()、values() 和 items() 函数来帮助解决这个问题。

EDIT: try something like this for ordering:

编辑:尝试这样的订购:

for x in sorted(l.keys()):
   for y in sorted(l[x].keys()):
       print l[x][y]

回答by razong

You create a one-dimensional list land want to use it as a two-dimensional list. Thats why you get an index error.

您创建了一个一维列表l并希望将其用作二维列表。这就是您收到索引错误的原因。

You have the following options: create a map and use the tuple t as index:

您有以下选择:创建一个映射并使用元组 t 作为索引:

l = {}
l[t] = something

and you will get entries in l as:

你将在 l 中获得条目:

{(1, 1): something}

if you want a traditional array structure I'll advise you to look at numpy. With numpy you get n-dimensional arrays with "traditional" indexing.

如果您想要传统的数组结构,我建议您查看numpy。使用 numpy,您可以获得带有“传统”索引的 n 维数组。

As I mentioned use numpy,

正如我提到的使用 numpy,

with numpy you can create a 2-dimensional array, filled with zeros or ones or ... Tha you can fill any desired value with indexing [x,y] as you desire. Of course you can iterate over rows and columns or the whole array as a list.

使用 numpy,您可以创建一个二维数组,填充零或一或......您可以根据需要使用索引 [x,y] 填充任何所需的值。当然,您可以将行和列或整个数组作为列表进行迭代。

回答by Nathan Ross Powell

If you know the size that you before hand,you can make a list of lists like this

如果你事先知道你的尺寸,你可以制作一个这样的列表

>>> x = 3
>>> y = 3
>>> l = [[None] * x for i in range(y)]
>>> l
[[None, None, None], [None, None, None], [None, None, None]]

Which you can then iterate like you originally suggested.

然后您可以像最初建议的那样进行迭代。

回答by Rodrigo

Extending the Nathan's answer,

扩展弥敦道的回答,

tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
x = max(tuples, key = lambda z : z[0])[0] + 1
y = max(tuples, key = lambda z : z[1])[1] + 1
l = [[None] * y for i in range(x)]

And then you can do whatever you want

然后你可以为所欲为

回答by Brian

The dict solutions given are probably best for most purposes. For your issue of iterating over the keys in order, generally you would instead iterate over the coordinate space, not the dict keys, exactly the same way you would have for your list of lists. Use .get and you can specify the default value to use for the blank cells, or alternatively use "collections.defaultdict" to define a default at dict creation time. eg.

给出的 dict 解决方案可能最适合大多数目的。对于按顺序迭代键的问题,通常您会迭代坐标空间,而不是 dict 键,这与您对列表列表的方式完全相同。使用 .get 并且您可以指定用于空白单元格的默认值,或者使用“ collections.defaultdict”在创建字典时定义默认值。例如。

for y in range(10):
    for x in range(10):
        value = mydict.get((x,y), some_default_value)
        # or just "value = mydict[x,y]" if used defaultdict

If you do need an actual list of lists, you can construct it directly as below:

如果你确实需要一个实际的列表列表,你可以直接构建它,如下所示:

max_x, max_y = map(max, zip(*tuples))
l=[[something if (x,y) in tuples else 0 for y in range(max_y+1)] 
     for x in xrange(max_x+1)]

If the list of tuples is likely to be long, the for performance reasons, you may want to use a set for the lookup,as "(x,y) in tuples" performs a scan of the list, rather than a fast lookup by hash. ie, change the second line to:

如果元组列表可能很长,出于性能原因,您可能希望使用集合进行查找,因为“ (x,y) in tuples”执行列表扫描,而不是通过哈希快速查找。即,将第二行更改为:

tuple_set = set(tuples)
l=[[something if (x,y) in tuple_set else 0 for y in range(max_y+1)] 
     for x in xrange(max_x+1)]

回答by Blair Conrad

As mentioned earlier, you can't make lists with gaps, and dictionaries may be the better choice here. The trick is to makes sure that l[t[0]]exists when you put something in position t[1]. For this, I'd use a defaultdict.

正如前面提到的,你不能制作有间隙的列表,字典可能是这里更好的选择。诀窍是确保l[t[0]]当您将某些东西放置到位时它存在t[1]。为此,我会使用defaultdict

import collections
tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
l = collections.defaultdict(dict)
for t in tuples:
    l[t[0]][t[1]] = something

Since lis a defaultdict, if l[t[0]]doesn't exist, it will create an empty dict for you to put your somethingin at position t[1].

由于l是 defaultdict,如果l[t[0]]不存在,它将为您创建一个空的 dict 以将您something的放在 position t[1]

Note: this ends up being the same as @unwesen's answer, without the minor tedium of hand-checking for existence of the inner dict. Chalk it up to concurrent answering.

注意:这最终与@unwesen 的答案相同,没有手动检查内部字典是否存在的繁琐。把它归结为并发回答。

回答by Dean

I think you have only declared a one dimensional list.

我认为您只声明了一个一维列表。

I think you declare it as

我想你把它声明为

l = [][]


Edit: That's a syntax error

编辑:这是一个语法错误

>>> l = [][]
  File "<stdin>", line 1
    l = [][]
           ^
SyntaxError: invalid syntax
>>>