簡體   English   中英

創建列表列表並追加列表

[英]Creating a list of lists and appending lists

a=[[2,3],[3,4]]
b=[[5,6],[7,8],[9,10]]
c=[[11,12],[13,14],[15,16],[17,18]]
c1=[[11,12],[13,14],[15,16],[17,18]]

listr=[]        
for number in range(96):
    listr.append(number)

list = [[]]*96
for e in a:
    for f in b:
        for g in c:
            for h in d:
                for i in listr:
                    list[i].append(e)
                    list[i].append(f)
                    list[i].append(g)
print list

對於這個簡單的問題,我確實有困難。 我想從上述列表中創建所有組合的列表。 如果列表重復,如[[2,3],[5,6],[11,12],[11,12]]不好,則第一個組合將為[[2,3],[ 5,6],[11,12],[13,14]。 這不是一個很好的開始,但我知道這並不難,但是我的編程技能卻不強。

最終列表看起來像

[[[2,3],[5,6],[11,12],[13,14]],[[2,3],[5,6],[11,12],[15,16]],[[2,3],[5,6],[11,12],[17,18]],...,[[3,4],[9,10],[15,16],[17,18]]]

我還想在每個單獨的列表中添加每個列表的第一個數字,並將它們加在一起。 [[31],[33],[35],...,[44]]

您可能要使用itertools.product解決此問題。

假設您希望將abcd的組合以4為一組(並且根據您的預期輸出,我認為您的c1有一個錯字,我稱之為d ,可以根據需要進行調整):

>>> import itertools
>>> a = [[2, 3], [3, 4]]  # are you sure this isn't actually [[1, 2], [3, 4]]?
>>> b = [[5, 6], [7, 8], [9, 10]]
>>> c = [[11, 12], [13, 14]]
>>> d = [[15, 16], [17, 18]]
>>>
>>> list(itertools.product(a, b, c, d))
[([2, 3], [5, 6], [11, 12], [15, 16]),  # pretty printed for readability
 ([2, 3], [5, 6], [11, 12], [17, 18]),
 ([2, 3], [5, 6], [13, 14], [15, 16]),
 ([2, 3], [5, 6], [13, 14], [17, 18]),
 ...
 ([3, 4], [9, 10], [13, 14], [17, 18])]
>>> len(list(itertools.product(a, b, c, d)))
24

順便說一句,當您嘗試創建一個int列表時,請使用:

listr=[]        
for number in range(96):
    listr.append(number)

您只需要執行以下操作:

listr = range(96)        # in Python2
# or
listr = list(range(96))  # in Python3

暫無
暫無

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

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