簡體   English   中英

將列表值與字典的公共鍵結合起來

[英]combine list values with common keys to a dictionary

我有一個清單

{ 'person1', '嗨', 'person1', '你在嗎?', 'person2', '你好', 'person1', 'Hru?', 'person2'', 'Good' }

我如何通過分組鍵和組合文本值將其轉換成字典? 預期結果:

{'person1':'嗨,你好嗎? Hru?', 'person2': '你好'}

注意:應該使用鍵名進行分組。 由於對話並不總是 person1 后跟 person2。

來自 aniketh 的代碼似乎有效。 我現在需要在 dataframe 上應用它,它有很多這樣的列表。

      chatid   list_of_convo
--------------------------------------------------------------------
0     12         {'person1', 'Hi','person1', 'You there?','person2', 
                  'Hello','person1', 'Hru?','person2','Good'}
1     21          {'person3', 'Hi','person3', 'You there?','person2', 
                   'Hello','person3', 'Hru?','person2','Good'}
2     34          {'person5', 'Hi','person5', 'You there?','person2', 
                   'Hello','person5', 'Hru?','person2','Good'}

上面的答案是:

def Convert(lst):
    dct = {}
    for ind in range(len(lst)):
      if ind % 2 == 0:
        if lst[ind] not in dct:
          dct[lst[ind]] = ""

    for ind in range(len(lst)):
      if ind % 2 == 1:
        dct[lst[ind - 1]] += lst[ind] + " "

    return dct

df['grouped'] = df['list_of_convo'].apply(Convert)

(供他人參考)

以下代碼可以工作:

lst = [ 'person1:', 'Hi', 'person2:', 'Hello', 'person1:', 'Hru?', 'person2:','Good' ]

dct = {}
for ind in range(len(lst)):
  if ind % 2 == 0:
    if lst[ind] not in dct:
      dct[lst[ind]] = ""

for ind in range(len(lst)):
  if ind % 2 == 1:
    dct[lst[ind - 1]] += lst[ind] + " "

print(dct)

Output:

{'person1:': 'Hi Hru? ', 'person2:': 'Hello Good '}

首先,要初始化列表,我們使用[]而不是{}

在創建字典dct之后,我們可以遍歷lst的每個偶數索引元素以獲取將成為dct鍵的元素( 'people1''people2' )。 首先,我們檢查密鑰是否已經存在於dct中,如果不存在,我們將其添加進去。

最后,我們遍歷奇數索引元素並將它們連接到它們各自鍵的值( lst中它們之前的元素)。

我希望這有幫助! 如果您需要任何進一步的幫助或說明,請告訴我!

注意:如果您關心 output 中的多余空間,請在打印之前添加以下代碼段以去除多余空間:

for key, value in dct.items():
  dct[key] = value[:-1]

第二個輸入:

lst = ['person1', 'Hi', 'person1', 'You there?', 'person2', 'Hello', 'person1', 'Hru?', 'person2','Good' ]

Output:

{'person1': 'Hi You there? Hru?', 'person2': 'Hello Good'}

嘗試:

pairs = zip(my_list[::2], my_list[1::2])
mydict = {}

for k, v in pairs:
   mydict[k] = (mydict.get(k, '') + ' ' + v).strip()

my_list[::2] 將從第一個元素(應該是您的鍵)開始獲取列表中的所有其他元素。 my_list[1::2] 會做同樣的事情,但從第二個元素開始,這應該是你的價值觀。 zip() 將生成一個元組列表,將每個鍵和值配對。 然后最后一行只是根據您對重復鍵的要求將該鍵值元組列表解析為實際的字典。

暫無
暫無

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

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