[英]Using list comprehension to “merge” a list within a list
所以我在列表中有列表:
woot = [['abc','efg', '4.3', '5.7', '80085'],['aba','bab', '1.0', '9.0', '3.0'], ... , ... ]
每個嵌套列表都是相同的:前兩個元素是由字母組成的字符串,其余的是由數字組成的字符串。
我正在嘗試將所有字符串數字轉換為浮點數並將每個相應的嵌套列表的字符串數字匯集到它自己的列表中(最終是一個雙嵌套列表),因此最終結果如下所示:
final = [['abc','efg', [ 4.3, 5.7, 80085]], ['aba','bab', [ 1.0, 9.0, 3.0]] , ... , ... ]
因此,我的方法是使用列表推導將字符串數字轉換為浮點數,然后將這些數字和字母字符串拆分為單獨的列表並合並它們。
bloop = [[float(x) for x in y[2:]] for y in woot]
bleep = [[x for x in y[:2]] for y in woot]
所以我最終得到:
bloop = [[ 4.3, 5.7, 8005.0],[ 1.0, 9.0, 3.0], ... , ... ]
bleep = [['abc','efg'],['aba','bab'], ... , ... ]
而這里是我崩潰的地方,似乎無法圍繞“合並”這些列表。
final = []
for i in bleep:
final.append(i)
for i in bloop:
final.append(i)
不幸的是,這只是將列表放在一起:
[['abc','efg'],['aba','bab'],[ 4.3, 5.7, 8005.0],[ 1.0, 9.0, 3.0]]
關於什么:
final = [x[:2] + [[float(f) for f in x[2:]]] for x in woot]
簡化您的邏輯:
final = []
for l in woot:
adjusted = l[:2]
adjusted.append( [float(x) for x in l[2:]] )
final.append(adjusted)
調試的難度是首先編寫代碼的兩倍。 因此,如果您盡可能巧妙地編寫代碼,那么根據定義,您不夠聰明,無法對其進行調試。
— Brian W. Kernighan and PJ Plauger in The Elements of Programming Style.
這是一個列表理解,可以產生您所需的輸出:
>>> [t[:2] + [[float(f) for f in t[2:]]] for t in woot]
[['abc', 'efg', [4.3, 5.7, 80085.0]], ['aba', 'bab', [1.0, 9.0, 3.0]]]
下面的想法使用列表推導和切片語法將每個子列表拆分為包含sub-0,sub-1的列表,然后是索引2..n中的項列表。 這是使用list
類型的+
運算符完成的。
為簡潔起見,我使用了map
而不是內部理解,但是如果你[float(ysub) for ysub in y[2:]]
使用[float(ysub) for ysub in y[2:]]
則沒有功能差異。
woot = [['abc','efg', '4.3', '5.7', '80085'],['aba','bab', '1.0', '9.0', '3.0']]
print [y[:2] + [map(float, y[2:])] for y in woot]
[['abc', 'efg', [4.3, 5.7, 80085.0]], ['aba', 'bab', [1.0, 9.0, 3.0]]]
這似乎有效:
final = [l[0:2]+[list(map(float,l[2:]))] for l in woot]
但也許我作弊因為我使用map
......
使用你的嗶嗶聲和bloop
bloop = [[ 4.3, 5.7, 8005.0],[ 1.0, 9.0, 3.0]]
bleep = [['abc','efg'],['aba','bab']]
final =[]
for i in range(len(bleep)):
final.append(bleep[i]+[bloop[i]])
print final
這里有很多很好的答案,我只想指出擴展語法通常更好。 另外,盡量避免嵌套列表推導。 幾乎總是更清楚的是只為每個級別的嵌套編寫一個函數,並在每個級別中放置一個列表理解。 所以我會這樣做:
def process_list(l) :
#processes the sub list
new_list = l[:2]
new_list.extend([float(x) for x in l[2:])
return new_list
result = [process_list(l) for l in original_list]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.