簡體   English   中英

合並兩個列表以基於一個列表的元素作為鍵(具有重復項)和其他作為值來制作字典

[英]Merge two list to make a dictionary based on elements of one list as key (with duplicates) and other as value

我有兩個存儲keyvalues的列表,如下所示:

key_list=['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
value_list=['(a)one', '(a)two', '(a)three', '(a)four', '(a)five', '(a)six', '(b)one', '(b)two', '(c)one', '(c)two', '(d)one']

我正在嘗試合並兩者並獲得這樣的新列表:

new key ['a', 'b', 'c', 'd']
new value ['(a)one--(a)two--(a)three--(a)four--(a)five--(a)six', '(b)one--(b)two', '(c)one--(c)two',(d)one]

之后,可以在沒有刪除重復的情況下制作字典。

我試過這段代碼。 你能幫助我嗎?

key_list=['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
value_list=['(a)one', '(a)two', '(a)three', '(a)four', '(a)five', '(a)six', '(b)one', '(b)two', '(c)one', '(c)two', '(d)one']
#-------------------------------
new_key=[]
new_value=[]
check=[]
for x,index in enumerate(key_list):
    if index in new_key:
        check.append(index)
        print("-dublicate \nx",x,"index",index,"\nadd check",check)
        try:
            x=x-1
            if check[x-1] == check[x]:
                print("inside the test")
                add=(value_list[x])+"--"+(value_list[x+1])
                new_value.append(add)
                del value_list[x]
        except:
            continue
    else:
        try:
            print("uniq element x - index:", x, index)
            new_key.append(index)
            new_value.append(value_list[x])
        except:
            continue
print("new key", new_key)
print("new value",new_value)

您可以使用collections.defaultdict()將默認值設置為dict object 中每個鍵的list ,然后您可以從列表中選擇 map 鍵值。

對於基於每個列表索引的 map 鍵和值,使用zip()

from collections import defaultdict

key_list=['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
value_list=['(a)one', '(a)two', '(a)three', '(a)four', '(a)five', '(a)six', '(b)one', '(b)two', '(c)one', '(c)two', '(d)one']

my_dict = defaultdict(list)
            
for key, value in zip(key_list, value_list):
    my_dict[key].append(value)

對於 map 鍵和值,基於值的字符串前綴為 " (key) " ,使用string.startswith(...)

my_dict = defaultdict(list)
for key in set(key_list):
    for value in value_list:
        if value.startswith('({})'.format(key)):
            my_dict[key].append(value)

對於上述列表, my_dict將保留上述代碼中的以下值:

{
    'a': ['(a)one', '(a)two', '(a)three', '(a)four', '(a)five', '(a)six'], 
    'b': ['(b)one', '(b)two'], 
    'c': ['(c)one', '(c)two'], 
    'd': ['(d)one']
}

現在您可以從my_dict以所需格式獲取new_keynew_value列表:

new_key = my_dict.keys()
# where `new_key` will hold:
# ['a', 'b', 'c', 'd']

new_value = ['--'.join(value) for value in my_dict.values()]
# where `new_value` will hold:
# ['(a)one--(a)two--(a)three--(a)four--(a)five--(a)six', '(b)one--(b)two', '(c)one--(c)two', '(d)one']

zip 並將兩個列表合並為一個 dataframe。 對變量進行分組並獲取唯一變量,然后為唯一變量中的每個值連接過濾器 dataframe。 zip 並列出結果。

key_list=['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'd']
value_list=['(a)one', '(a)two', '(a)three', '(a)four', '(a)five', '(a)six', '(b)one', '(b)two', '(c)one', '(c)two', '(d)one']

data=list(zip(key_list,value_list))
df=pd.DataFrame(data,columns=['variable','phrase'])
unique_variables=list(df.groupby('variable').groups)
phrases=[]
for key in unique_variables:
    filter=df['variable']==key
    phrases.append("".join(df[filter]['phrase']))

print(list(zip(unique_variables,phrases)))

output:

[('a', '(a)one(a)two(a)three(a)four(a)five(a)six'), ('b', '(b)one(b)two'), ('c', '(c)one(c)two'), ('d', '(d)one')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM