我有一个看起来像
的列表[['password', '_rev', '_id', 'username'],
['password', '_rev', '_id', 'username', 'name'],
['password', '_rev', '_id', 'username'],
['password', '_rev', '_id', 'username','country':'india']]
以上是仅包含4个数据的示例。就我而言,我可以有成千上万个与上面相似的条目。
我想比较列表中的数据并将列表合并到一个列表中。
必填:
['password', '_rev', '_id', 'username', 'name', 'country']
如何使其成为可能并更快地获得输出?
答案 0 :(得分:1)
from itertools import chain
l = [['password', '_rev', '_id', 'username'], ['password', '_rev', '_id', 'username', 'name'], ['password', '_rev', '_id', 'username'],['password', '_rev', '_id', 'username','country']]
list(set(chain(*l)))
输出-
['username', '_rev', '_id', 'name', 'password', 'country']
答案 1 :(得分:0)
尝试使用dict.fromkeys
并展平列表:
print(list(dict.fromkeys([x for i in l for x in i])))
或将set
与sorted
:
flat = [x for i in l for x in i]
print(sorted(set(flat), key=flat.index))
答案 2 :(得分:0)
简单代码
l = [['password', '_rev', '_id', 'username'], ['password', '_rev', '_id', 'username', 'name'], ['password', '_rev', '_id', 'username'],['password', '_rev', '_id', 'username','country']]
ll = []
for i in l:
ll.extend(i)
#Remove dupes
gl = list(set(ll))
print(gl)
输出
['username', '_id', 'name', 'country', '_rev', 'password']
答案 3 :(得分:0)
尝试此解决方案!
arr = [['password', '_rev', '_id', 'username'], ['password', '_rev', '_id', 'username', 'name'], ['password', '_rev', '_id', 'username'],['password', '_rev', '_id', 'username','country']]
new_arr = arr[0]
for i in range(1,len(arr)):
for j in range(0,len(arr[i])):
if not arr[i][j] in new_arr:
new_arr.append(arr[i][j])
print(new_arr)
输出:
['password', '_rev', '_id', 'username', 'name', 'country']