我有兩個清單。
第一個串列是作者串列。第二個串列有兩種型別的物件,作者和文本。文本被分成單詞。第二個串列的結構是有一個作者在前和幾個詞一起組成他的演講。在第二個串列中,有幾位作者發表了他們的演講。
authors = ['M. Maxime Gremet', 'M. le président.', 'M.Claude Goasgu', 'M.Jean-Marc Ayr',
'M.Maxime Gremet', 'M.Roland Chassa', 'M.le président.']
authors_and_words = ['M. le président.', "Conformément au premier alinéa de l'article 28 de la Constitution, je déclare ouverte la session ordinaire de 2003-2004.", "Mes chers collègues, permettez-moi d'abord de vous dire combien je suis heureux de vous retrouver tous.", 'M. Maxime Gremetz.', 'Nous aussi !']
我想從第二個串列中提取一個作者和他的演講詞到一個新串列中(或者甚至更好的字典)。
輸出字典將具有以下結構:
{'author': ['word1', 'word2', 'word3']}
如果我們采用實際串列,則解決方案將是以下串列。
solution = [{'M. le président.': ["Conformément au premier alinéa de l'article 28 de la Constitution, je déclare ouverte la session ordinaire de 2003-2004.", "Mes chers collègues, permettez-moi d'abord de vous dire combien je suis heureux de vous retrouver tous."]}, {'M. Maxime Gremetz.':['Nous aussi !']}]
我嘗試使用不同型別的回圈,但我很難保持第二個串列的狀態。我想有一個演算法解決方案,但不幸的是我對演算法沒有太多經驗。
uj5u.com熱心網友回復:
檢查一個元素authors_and_words是否在authors里面很容易:使用in關鍵字。
現在,遍歷 的每個元素authors_and_words,如果它是作者,那就是你的字典鍵。每當你找到一個新作者時,創建一個字典來存盤他們的行,并將這個字典附加到包含所有作者行的主串列中:
conversation = ["junk value"] # Initialize with a junk value to prevent error in `conversation[-1]` in the first loop
for line in authors_and_words:
# < is an author> and <prev author is different >
if line in authors and line not in conversation[-1]:
d = {line: []} # Create an empty dict for this author
conversation.append(d)
else:
author = list(conversation[-1].keys())[0] # Get author from the last dict in the list
conversation[-1][author].append(line)
result = conversation[1:] # Discard junk element from result
這給出了:
[{'M. le président.': ["Conformément au premier alinéa de l'article 28 de la Constitution, je déclare ouverte la session ordinaire de 2003-2004.",
"Mes chers collègues, permettez-moi d'abord de vous dire combien je suis heureux de vous retrouver tous."]},
{'M. Maxime Gremetz.': ['Nous aussi !']}]
注意1:如果authors是一個長串列,將其轉換為一個集合并檢查該集合中的成員會更有效。
注意2:我修復了您authors串列中的拼寫錯誤以允許line in authors作業。如果不是這種情況,并且您希望能夠處理此類拼寫錯誤,那么您需要將 替換line in authors為list_start_match(authors, line),并使用以下定義list_start_match。在這種情況下,您將無法使用集合進行快速成員資格檢查:
def list_start_match(lst, val):
for elem in lst:
if elem.startswith(val): return True
return False
在這里,我.startswith用來檢查每個元素是否lst以val. 如果您有不同的標準來匹配給定部分值的作者,您可以使用它。
注意 3:您的預期輸出是字典串列,而不是字典。你可以有一個 dict 作為輸出,但是你會失去人們說話的順序,因為 dicts 每個鍵只能有一個值。此值可以是一個list,它允許您為每個人設定多條對話“線”,但由于在多人之間交替進行對話而失敗。無論如何,這似乎不是您要尋找的東西,所以我想這是一個有爭議的問題。
注意 4:如果您可以控制輸出的模式,我強烈建議您不要使用以您的作者命名的鍵。這使得更難確定誰是作者(author = list(conversation[-1].keys())[0]我們在上面所做的惡作劇)。
相反,請考慮將輸出的每個元素更改為以下內容:
{"author": 'M. Maxime Gremetz.',
"lines": ['Nous aussi !']}
它允許您使用密鑰訪問每個片段的作者。"author"如果您決定這樣做,則必須像這樣修改代碼:
conversation = ["junk value"] # Initialize with a junk value to prevent error in `conversation[-1]` in the first loop
for line in authors_and_words:
# < is an author> and <prev author is different >
if line in authors and line not in conversation[-1]:
d = {"author": line, "lines": []} # Create an empty dict for this author
conversation.append(d)
else:
conversation[-1]["lines"].append(line)
result = conversation[1:] # Discard junk element from result
這給出了以下內容:
[{'author': 'M. le président.',
'lines': ["Conformément au premier alinéa de l'article 28 de la Constitution, je déclare ouverte la session ordinaire de 2003-2004.",
"Mes chers collègues, permettez-moi d'abord de vous dire combien je suis heureux de vous retrouver tous."]},
{'author': 'M. Maxime Gremetz.', 'lines': ['Nous aussi !']}]
uj5u.com熱心網友回復:
Pranav 為我的問題提供了一個很好的答案,但后來我完成了自己的解決方案。它不像他的那樣優雅,但也很有效。
solution = []
items_counter = 0
authors_counter = 0
while items_counter < len(authors_and_words):
current_author = ''
for i in authors_and_words:
if i in authors:
temp_dict = {}
temp_dict[i] = []
items_counter =1
current_author = i
solution.append(temp_dict)
authors_counter =1
else:
items_counter = 1
temp_dict[current_author].append(i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524610.html
標籤:Python算法循环
上一篇:立方體網格上的光線投射?
