[英]Making a new list with tuples based on strings in the list
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
每個數字代表一個人。 因此,列表中有5個人,從0到4。 L[0]
始終顯示列表中有多少人。
L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]
人"0"
與1
和2
配對。 因此,它在一個元組中具有1, 2
的列表。 我獲得以上結果的方法是將L[1]
的第一個字符與列表的末尾進行比較。 如果L[1]
中的第一個字母與L[2]
的第一個字母匹配,則會將L[2]
中的第二個字母與L[1]
的第二個字母捆綁在一起。 最后,新列表在元組中與0
配對。 順便說一句,我無法提出可以檢查字符串中第一個字母的東西。 我不確定這種方法是否正確。
我努力在上面列出這樣的清單L1
。 誰能告訴我我對這個問題的解決方法是否正確? 如果有誤,請簡要提示我解決此問題。
使用列表理解
考慮到L[0]
,在所需范圍內創建了一個列表
使用startswith
檢查元素和其他項目之間的匹配
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])] # required list
L2 = [ (i, [ int(x[-1]) for x in L if str(x).startswith(str(i)) ]) for i in range(int(L[0])-1) ]
產量
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
最好的辦法是先使用defaultdict
:
from collections import defaultdict
from itertools import islice
result = defaultdict(list)
for li in islice(L,1,None):
h, *others = map(int,li.split())
for other in others:
result[h].append(other)
或適用於python-2.x的版本 :
from collections import defaultdict
from itertools import islice
result = defaultdict(list)
for li in islice(L,1,None):
data = map(int,li.split())
h = data[0]
for other in data[1:]:
result[h].append(other)
然后我們獲得該詞典的items
:
L1 = list(result.items())
這將產生:
>>> L1
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
請注意,在這種情況下,項目沒有順序:因為Python中的字典通常沒有順序(CPython中的最新實現是有順序的,但這被視為實現細節)。
但是將字典轉換回列表是不合邏輯的,因為字典的優點是可以快速查找(在O(1)中為常數時間)。
我們可以通過編寫以下內容使最后一部分更優雅:
from collections import defaultdict
result = defaultdict(list)
for li in islice(L,1,None):
h, *others = map(int,li.split())
result[h] += others
而不是列表,請使用dict並使用此模式,而無需導入任何外部模塊。
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
final_dict={}
new=[]
for item in L:
if not len(item)<2:
if int(item[0]) not in final_dict:
final_dict[int(item[0])]=[int(item[2])]
else:
final_dict[int(item[0])].append(int(item[2]))
print(final_dict)
輸出:
{0: [1, 2], 1: [3], 2: [3, 4], 3: [4]}
或者,如果您希望結果在列表中,則在上面的代碼中添加以下行:
print([(key,value) for key,value in final_dict.items()])
輸出:
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
我建議您使用dictionary
的形式,以便以后更輕松地處理數據。 因此,這里最好使用defualtdict
。
>>> from collections import defaultdict
>>> L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
>>> n = int(L.pop(0)) #number of people
>>> d = defaultdict(list)
>>> for ele in L:
x, y = map(int, ele.split())
d[x].append(y)
>>> d
=> defaultdict(<class 'list'>, {0: [1, 2], 1: [3], 2: [3, 4], 3: [4]})
如果需要具有該list
格式,請使用dict.items()
並鍵入將其dict.items()
為list
>>> l1 = list(d.items())
>>> l1
=> [(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
這是一個itertools.groupy
解決方案。 (注釋行還考慮反向對。)
import itertools as it
import operator as op
def L1(L):
# split pairs
L = [p.split() for p in L[1:]]
# convert to int
L = [(int(P1), int(P2)) for P1, P2 in L]
LL = sorted(L)
# # add reversed and sort
# LL = sorted(L + [P[::-1] for P in L])
# group by first element
res = it.groupby(LL, op.itemgetter(0))
# make proper lists
return [(k, [P[1] for P in v]) for k, v in res]
輸出(例如L
):
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.