gpt4 book ai didi

python - 将列表转换为字符串三元组序列

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:45 24 4
gpt4 key购买 nike

我想像这样转换一个列表:

["Red", "Green", "Blue"]

进入字符串三元组的元组序列:

[("RED", "Red", ""), ("GREEN", "Green", ""), ("BLUE", "Blue", "")]

直到现在我一直使用这个方法:

def list_to_items(lst):
items = []
for i in lst:
items.append((i.upper(), i, ""))
return items

但是感觉有点丑。有没有更好/更 pythonic 的方式来做到这一点?

最佳答案

类似于列表理解,但有点不同。

这是 map 函数。

lst = ["Red", "Green", "Blue"]
new_lst = map(lambda x: (x.upper(), x, ""), lst)

它基本上根据您作为第一个参数输入的函数逐个更改列表的每个元素。在这种情况下:

lambda x: (x.upper(), x, "")

如果您不知道lambda 是什么,它几乎就像在高中数学中一样:

f(x) = (x.upper(), x, "") # basically defines a function in one line.

关于python - 将列表转换为字符串三元组序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34831224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com