[英]How to find common elements inside a list
我有一個看起來像[1,2,1,0,1,1,0,3 ..]的列表l1。 我想為每個元素查找與該元素具有相同值的元素索引。
例如,對於列表中的第一個值1,它應該列出列表中存在1的所有索引,並且應該對列表中的每個元素重復相同的索引。 我可以編寫一個函數來遍歷列表,但想檢查是否有任何預定義的函數。
我是從Pandas數據框列中獲取列表的,所以最好知道series / dataframe庫是否提供任何此類功能
您可以使用numpy.unique
,它也可以返回相反的值。 可以使用numpy.where
來重建索引:
In [49]: a = [1,2,1,0,1,1,0,3,8,10,6,7]
In [50]: uniq, inv = numpy.unique(a, return_inverse=True)
In [51]: r = [(uniq[i], numpy.where(inv == i)[0]) for i in range(uniq.size)]
In [52]: print(r)
[(0, array([3, 6])), (1, array([0, 2, 4, 5])), (2, array([1])), (3, array([7])), (6, array([10])), (7, array([11])), (8, array([8])), (10, array([9]))]
我嘗試過蠻力..也許你可以優化
這是python3代碼
L = [1,2,1,0,1,1,0,3]
D = dict()
for i in range(len(L)):
n =[]
if L[i] not in D.keys():
for j in range(len(L)):
if L[i] == L[j]:
n.append(j)
D[L[i]] = n
for j in D.keys():
print(j,"->",D.get(j))
您也可以嘗試如下操作:
import pandas as pd
df = pd.DataFrame({'A': [1,2,1,0,1,1,0,3]})
uni = df['A'].unique()
for i in uni:
lists = df[df['A'] == i].index.tolist()
print(i, '-->', lists)
輸出:
1 --> [0, 2, 4, 5]
2 --> [1]
0 --> [3, 6]
3 --> [7]
您可以使用defaultdict
實現此目的。
from collection import defaultdict
input = [1,2,1,0,1,1,0,3]
#Dictionary to store our indices for each value
index_dict = defaultdict(list)
#Store index for each item
for i, item in enumerate(input):
index_dict[item].append(i)
如果想要一個包含與輸入列表中的相應元素相同的元素索引的列表,則只需創建對字典的引用即可:
same_element_indices = [index_dict[x] for x in input]
這樣做的好處是,每個相同的元素僅引用一個對象。
輸出為:
[[0, 2, 4, 5],
[1],
[0, 2, 4, 5],
[3, 6],
[0, 2, 4, 5],
[0, 2, 4, 5],
[3, 6],
[7]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.