簡體   English   中英

Python:如何為列表的每個元素添加另一個列表中的每個元素?

[英]Python : How to add for each element of a list every element from another list?

我對 Python 真的很陌生,我想管理我創建的一些列表。 因此,在列表 AI 中具有年份的最后兩位數字,在列表 BI 中具有從 000 到 999 的數字。

對於列表 A 中的每一年,我想使用循環添加列表 BI 中的每個數字猜測...

listA = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']

listB = ['000', '001', '002', '003', ...]

* 某事循環 *

listC = ['00000', '00001', '00002', ...]

謝謝!

使用itertools.product

from itertools import product

listA = ['00', '01', '02', '03']
listB = ['000', '001', '002', '003']

listC = [a + b for a, b in product(listB, listA)] # ['00000', '00001', '00002', ...]

product函數遍歷提供的可迭代對象的笛卡爾積(所有組合的 k 元組從每個列表中抽取一個)。 字符串連接用於連接元組 ( a + b ) 的元素。 列表理解將它們全部放入一個大列表中。

雖然itertools.product很方便,但一個簡單的嵌套itertools.product也同樣適用:

list_a = ['00', '01', '02', '03']  # Python conventions call for snake_case
list_b = ['000', '001', '002', '003']

list_c = [b + a for b in list_b for a in list_a]
# ['00000', '00001', '00002', '00003', ... ]

請注意,第一個for范圍更廣,與自然英語相比,這有時似乎違反直覺。

您將需要遍歷listB ,因此您將執行以下操作:

for itemB in listB:

然后每個這些項目中,你需要在每一個元素匹配它listA ,所以你會做另一個循環嵌套在listA

for itemA in listA:

然后在兩個循環中,您將擁有itemAitemB所有組合。 所以你只需要連接它們並將它們添加到輸出列表中。

完整解決方案

ouptut = []
for itemB in listB:
  for itemA in listA:
    output.append(itemB + itemA)

另一個解決方案中提到的itertools.product可以為您提供更簡潔的解決方案,因為它替換了兩個for循環。


> Code to reproduce listA

listA = []
for i in range(0,10):
    for j in range(0,10):
        e = str(i)+str(j)
        listA.append(e)
print(listA)

> Code to reproduce listB


listB = []
for i in range(0,10):
    for j in range(0,10):
        for k in range(0,10):
            e = str(i)+str(j)+str(k)
            listB.append(e)
print(listB)

> Now we just iterate over each element of listA and append one by one each element of listB, and keep appending the result to listC to get the final output list



listC = []
for i in listA:
    for j in listB:

        listC.append(i+j)
print(listC)

您可以使用內置函數 zip()

例如:

class SumList():

    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = [ x + y for x,y in zip(self.mylist, other.mylist)]
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

cc = SumList([1,2,3,4])
dd = SumList([100,200,300,400])    
ee = cc + dd
print(ee)

暫無
暫無

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

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