[英]Appending new values to a python list
Lets say I have two lists: 可以说我有两个列表:
x = [1,2,3,4]
y = [1,4,7,8]
I want to append to x any values in y that are not already in x. 我想将x中尚未存在的y中的任何值附加到x中。 I can do this easily with a loop: 我可以通过循环轻松地做到这一点:
for value in y:
if value not in x:
x.append(value)
But I am wondering if there a more Pythonic way of doing this. 但是我想知道是否还有更多的Python方式可以做到这一点。
Something like this: 像这样:
In [22]: x = [1,2,3,4]
In [23]: y = [1,4,7,8]
In [24]: x += [ item for item in y if item not in x]
In [25]: x
Out[25]: [1, 2, 3, 4, 7, 8]
+=
acts as list.extend
, so the above code is equivalent to : +=
用作list.extend
,因此上面的代码等效于:
In [26]: x = [1,2,3,4]
In [27]: lis = [ item for item in y if item not in x]
In [28]: x.extend(lis)
In [29]: x
Out[29]: [1, 2, 3, 4, 7, 8]
Note that if the size of list
x
is huge and your list x/y contain only immutable(hashable) items then you must usesets
here, as they will improve the time complexity toO(N)
. 请注意,如果列表x
的大小很大,并且列表x / y仅包含不可变(可哈希)项,则您必须在此处使用sets
,因为它们会将时间复杂度提高到O(N)
。
>>> x = [1,2,3,4]
>>> y = [1,4,7,8]
>>> set_x = set(x) # for fast O(1) amortized lookup
>>> x.extend(el for el in y if el not in set_x)
>>> x
[1, 2, 3, 4, 7, 8]
If you did not care about the order of the result you could do: 如果您不关心结果的顺序,则可以执行以下操作:
>>> x=[1,2,3,4]
>>> y=[1,4,7,8]
>>> x = list(set(x + y))
>>> x
[1, 2, 3, 4, 7, 8]
x = [1,2,3,4]
y = [1,4,7,8]
Now we want to append to x any values in y that are not already in x. 现在我们想将x中尚未存在的y中的任何值附加到x上。 This can be done easily as: 这很容易做到:
temp = [item for item in y if item not in x]
x.extend(temp)
This will first put all the elements which are not in x but are present in y in a list called temp. 这将首先将所有不在x中但在y中存在的元素放入称为temp的列表中。 Now we shall extend list x to include elements from temp. 现在,我们将扩展列表x以包括temp中的元素。 Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.