[英]Python List Comprehension with two cycles
我是Python的初學者。
我學習了列表理解,但是我的代碼很糟糕,因為列表理解是錯誤或缺失的:
我嘗試了很多事情,但結果是生成器或錯誤。 你能給我建議...嗎?
謝謝。 宏cer
import itertools as it
aT=list(it.permutations([4,3,3,0],3))
uT=list(set(aT))
# convert uniqueTimes list of tuples to list of lists
uT=[list(el) for el in uT]
uTt=[el[0]+el[1]+el[2] for el in uT] #It is wrong, I want universal list comprehension :-( when I change members of permutation, e.g.it.permutations([5,4,3,2,1],4))
uTs=[] #It is wrong too, I want universal list comprehension :-(
a=""
for m in range(len(uT)):
for n in range(len(uT[m])):
a+=str(uT[m][n])
uTs.append(a)
a=""
uTcombine=list(it.zip_longest(uTs,uTt)) #result as I expected, but the algorithm is "non comperhesion"
print(uT)
print(uTcombine)
從此(uT-列表列表,其中每個內部列表都是唯一的)
[[0,3,3],[3,4,3],[0,3,4],[3,0,3],[3,4,0],[3,0,4],[ 4,0,3],[4,3,3],[3,3,4],[3,3,0],[0,4,3],[4,3,0]]
我需要那個(uTcombine-元組列表,其中元組中的第一個是[0,3,3] =>'033',第二個是列表項的總和[0,3,3] => 6
[('033',6),('343',10),('034',7),('303',6),('340',7),('304',7),( '403',7),('433',10),('334',10),('330',6),('043',7),('430',7)]
您可以使用標准庫中的現有函數,而不必在可能的情況下編寫自己的函數:
uT = [(''.join(map(str, el)), sum(el)) for el in uT]
在這種情況下:
''.join(map(str, el))
將排列轉換為所需的字符串表示形式(0, 3, 3, )
0,3,3 (0, 3, 3, )
-> '033'
,首先將每個項目覆蓋為字符串(使用map(str, el)
) ,然后加入字符串。
sum(el)
總結了排列(0, 3, 3, )
0,3,3 (0, 3, 3, )
-> 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.