取不同字符串中的相同元素之一
take one of the same elements in different strings
我想把我拥有的三个不同的系列结合起来。我还需要为每个元素提供奇点。输出顺序不是important.Example 3个数组:
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
结果
result=["apple","banana","orange","cherry","grappe"]
您可以使用 set
并这样做:
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
result = list(set(a + b + c))
>>> result = ["apple","banana","orange","cherry","grappe"]
a = ["apple", "banana", "orange"]
b = ["apple", "banana"]
c = ["cherry", "grappe"]
lst = list(set(a + b + c))
print(lst)
['banana', 'apple', 'cherry', 'grappe', 'orange']
查看 set
的文档以了解它在做什么。
您可以使用 itertools.chain
然后转换为设置以删除重复项,然后转换回列表(也进行了排序):
import itertools
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
d = sorted(list(set(list(itertools.chain(a,b,c)))))
print(d)
您可以使用 set
删除重复项:
list(set(a+b+c))
如果你想保持第一次出现的顺序,正如你的示例输出所建议的那样,一种方法是创建一个以你的数据作为键的字典,利用字典自 Python 以来排序的事实3.7:
from itertools import chain
a = ["apple","banana","orange"]
b = ["apple","banana"]
c = ["cherry","grappe"]
d = {key: None for key in chain(a, b, c)}
result = list(d.keys())
print(result)
# ['apple', 'banana', 'orange', 'cherry', 'grappe']
a = ["apple", "banana", "orange"]
b = ["apple", "banana"]
c = ["cherry", "grappe"]
result = a + b + c # marge all lsit
result = list(dict().fromkeys(result)) # remove duplicate
print(result)
参考:https://www.w3schools.com/python/python_howto_remove_duplicates.asp
我想把我拥有的三个不同的系列结合起来。我还需要为每个元素提供奇点。输出顺序不是important.Example 3个数组:
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
结果
result=["apple","banana","orange","cherry","grappe"]
您可以使用 set
并这样做:
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
result = list(set(a + b + c))
>>> result = ["apple","banana","orange","cherry","grappe"]
a = ["apple", "banana", "orange"]
b = ["apple", "banana"]
c = ["cherry", "grappe"]
lst = list(set(a + b + c))
print(lst)
['banana', 'apple', 'cherry', 'grappe', 'orange']
查看 set
的文档以了解它在做什么。
您可以使用 itertools.chain
然后转换为设置以删除重复项,然后转换回列表(也进行了排序):
import itertools
a=["apple","banana","orange"]
b=["apple","banana"]
c=["cherry","grappe"]
d = sorted(list(set(list(itertools.chain(a,b,c)))))
print(d)
您可以使用 set
删除重复项:
list(set(a+b+c))
如果你想保持第一次出现的顺序,正如你的示例输出所建议的那样,一种方法是创建一个以你的数据作为键的字典,利用字典自 Python 以来排序的事实3.7:
from itertools import chain
a = ["apple","banana","orange"]
b = ["apple","banana"]
c = ["cherry","grappe"]
d = {key: None for key in chain(a, b, c)}
result = list(d.keys())
print(result)
# ['apple', 'banana', 'orange', 'cherry', 'grappe']
a = ["apple", "banana", "orange"]
b = ["apple", "banana"]
c = ["cherry", "grappe"]
result = a + b + c # marge all lsit
result = list(dict().fromkeys(result)) # remove duplicate
print(result)
参考:https://www.w3schools.com/python/python_howto_remove_duplicates.asp