Python 访问列表列表中的项目

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

Access item in a list of lists

pythonlist

提问by John

If I have a list of lists and just want to manipulate an individual item in that list, how would I go about doing that?

如果我有一个列表列表并且只想操作该列表中的单个项目,我该怎么做?

For example:

例如:

List1 = [[10,13,17],[3,5,1],[13,11,12]]

What if I want to take a value (say 50) and look just at the first sublist in List1, and subtract 10 (the first value), then add 13, then subtract 17?

如果我想取一个值(比如 50)并只查看 中的第一个子列表List1,然后减去 10(第一个值),然后加上 13,然后减去 17,该怎么办?

回答by arshajii

You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17is element 2in list 0, which is list1[0][2]:

您可以通过首先指定您感兴趣的列表,然后指定您想要该列表的哪个元素来访问列表列表中的元素。例如,17is element 2in list 0,即list1[0][2]

>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17

So, your example would be

所以,你的例子是

50 - list1[0][0] + list1[0][1] - list1[0][2]

回答by Donald Miner

50 - List1[0][0] + List[0][1] - List[0][2]

List[0]gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

List[0]为您提供列表中的第一个列表(尝试print List[0])。然后,您再次对其进行索引以获取该列表的项目。可以这样想:(List1[0])[0].

回答by Joran Beasley

List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num

回答by rajpy

for l in list1:
    val = 50 - l[0] + l[1] - l[2]
    print "val:", val

Loop through list and do operation on the sublist as you wanted.

循环遍历列表并根据需要对子列表进行操作。

回答by Ashwini Chaudhary

You can use itertools.cycle:

您可以使用itertools.cycle

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sumwould return something like this:

这里的生成器表达式sum将返回如下内容:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use ziphere:

您也可以zip在这里使用:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

回答by Phil

This code will print each individual number:

此代码将打印每个单独的数字:

for myList in [[10,13,17],[3,5,1],[13,11,12]]:
    for item in myList:
        print(item)

Or for your specific use case:

或者对于您的特定用例:

((50 - List1[0][0]) + List1[0][1]) - List1[0][2]