Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在列表中附加多个对象?_Python_List_Append - Fatal编程技术网

Python 如何在列表中附加多个对象?

Python 如何在列表中附加多个对象?,python,list,append,Python,List,Append,因此,我得到了一个名为otherlist的列表,我想从list1中添加一些对象。问题是,我只得到了他们的订单号,而不是这些数字的实际值。例如: otherlist.append(list1[a,a+20,a+20*2,a+20*3]) (其中a是一个不断变化的数字) 是的,正如你可能已经注意到的那样,我们希望排名第20位 如何做到这一点。我得到错误消息:TypeError:list索引必须是整数,而不是tuplePythonlist索引不能是tuple(逗号分隔的索引);一次只能索引一个值 使

因此,我得到了一个名为
otherlist
的列表,我想从
list1
中添加一些对象。问题是,我只得到了他们的订单号,而不是这些数字的实际值。例如:

otherlist.append(list1[a,a+20,a+20*2,a+20*3])
(其中
a
是一个不断变化的数字) 是的,正如你可能已经注意到的那样,我们希望排名第20位


如何做到这一点。我得到错误消息:
TypeError:list索引必须是整数,而不是tuple

Python
list
索引不能是tuple(逗号分隔的索引);一次只能索引一个值

使用
operator.itemgetter()
获取多个索引:

from operator import itemgetter

otherlist.extend(itemgetter(a, a + 20, a + 20 * 2, a + 20 * 3)(list1))
或使用生成器表达式:

otherlist.extend(list1[i] for i in (a, a + 20, a + 20 * 2, a + 20 * 3))
my_list.extend(list1[a + 20*i] for i in range(4))
甚至

otherlist.extend(list1[a + 20 * i] for i in range(4))

请注意,我使用
list.extend()
将单个值添加到
otherlist
,使其增加4个元素。

Python
list
索引不能是元组(逗号分隔的索引);一次只能索引一个值

使用
operator.itemgetter()
获取多个索引:

from operator import itemgetter

otherlist.extend(itemgetter(a, a + 20, a + 20 * 2, a + 20 * 3)(list1))
或使用生成器表达式:

otherlist.extend(list1[i] for i in (a, a + 20, a + 20 * 2, a + 20 * 3))
my_list.extend(list1[a + 20*i] for i in range(4))
甚至

otherlist.extend(list1[a + 20 * i] for i in range(4))

请注意,我使用
list.extend()
将单个值添加到
otherlist
,使其增加4个元素。

使用
list.extend
和生成器表达式:

otherlist.extend(list1[i] for i in (a, a + 20, a + 20 * 2, a + 20 * 3))
my_list.extend(list1[a + 20*i] for i in range(4))
演示:

>>> lis = []
>>> list1 = range(1000)
>>> a = 2
>>> lis.extend(list1[a + 20*i] for i in range(4))
>>> lis
[2, 22, 42, 62]

使用
列表。使用生成器表达式扩展

otherlist.extend(list1[i] for i in (a, a + 20, a + 20 * 2, a + 20 * 3))
my_list.extend(list1[a + 20*i] for i in range(4))
演示:

>>> lis = []
>>> list1 = range(1000)
>>> a = 2
>>> lis.extend(list1[a + 20*i] for i in range(4))
>>> lis
[2, 22, 42, 62]