Python 如何使用 lambda 函数附加到列表中的每个字符串?

Python how do I append to every string in list using lambda function?

我正在尝试了解 lambda 函数,我希望代码能够:

  1. 在列表中的字符串末尾添加斜杠“/”'techCodeList'
  2. 将 'finishList' 中的每个项目添加并附加到 'techCodeList' 中的每个条目,每次都附加到 'combinedCodeList'(因此 combinedCodeList = ['a/ABUL', 'a/BEL', 'a/PBL'] 等)

我可以使用其他方法来完成,但我想尝试使用 lambda,它是否可行?如果可行,我将如何实现?我的代码如下:

#example shortened
class myClass:
    def __init__(self):
        self.techCodeList = ('a','b','c')

        def applyCodes(self):
                self.combinedCodeList = list()
                finishList = ["ABUL","BEL","PBL","PBUL","ABL","SBL","SBSL","SBUL","PNP","SNP","PCP","SCP","NBP","ASP","ACP","SAL","SAS","AMB","CBP","HBN","MBL","MWL","HBB","SPE","PBUL/SAMPLE"]#list to append to techcodelist
                len1 = len(self.combinedCodeList)
                arrayCounter = 0
                for i in self.techCodeList:
                    for _ in finishList:
                        print (arrayCounter)
                        self.techCodeList = list(map(lambda orig_string: orig_string + '/', self.techCodeList[arrayCounter]))
                        self.techCodeList = list(map(lambda orig_string: orig_string + finishList[arrayCounter], self.techCodeList[arrayCounter]))
                        self.combinedCodeList.append(self.techCodeList[arrayCounter])
                        if arrayCounter == len(self.techCodeList) - 1:
                            break
                        arrayCounter = arrayCounter + 1

                print (self.combinedCodeList)

myClass()

这里是 combinedCodeList 中的结果:

['aABUL', '/BEL', '/BEL', '/BEL']

如果您有任何其他关于良好习惯的建议或对我的代码的建议,请随时留下,我仍然在学习。谢谢

如果我理解正确的话,您想在技术代码和完成列表中的所有条目之间创建一个详尽的组合。

为此,您可以使用如下列表推导式:

tech_code_list = ["a", "b", "c"]
finish_list = ["ABUL","BEL","PBL","PBUL","ABL","SBL","SBSL","SBUL","PNP","SNP","PCP","SCP","NBP","ASP","ACP","SAL","SAS","AMB","CBP","HBN","MBL","MWL","HBB","SPE","PBUL/SAMPLE"]
               

combined_code_list = [
    tech_code + "/" + finish for tech_code in tech_code_list for finish in finish_list
]

print(combined_code_list) 
# will print: ['a/ABUL', 'a/BEL', 'a/PBL', 'a/PBUL', ... ]

iterools.product 为您提供来自两个列表的所有成对组合。因为你想使用 lambda 我们在 map 函数

中这样做
from itertools import product
list(map(lambda p: p[0] + '/' + p[1], product(tech_code_list, finish_list)))

输出:

['a/ABUL',
 'a/BEL',
 'a/PBL',
 'a/PBUL',
 'a/ABL',
...
]