Python 将列表转换为字符串三元组序列
我想转换如下列表:Python 将列表转换为字符串三元组序列,python,list,tuples,Python,List,Tuples,我想转换如下列表: ["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 item
["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
但是感觉有点难看。有没有更好/更符合Python的方法来实现这一点?返回语句中的代码称为列表理解
def list_to_items(items):
return [(i.upper(), i, "") for i in items]
您可以找到更多信息返回语句中的代码称为列表理解
def list_to_items(items):
return [(i.upper(), i, "") for i in items]
您可以找到更多信息您可以使用理解:
def list_to_items(lst):
return [(item.upper(), item.title(), '') for item in lst]
您可以使用以下理解:
def list_to_items(lst):
return [(item.upper(), item.title(), '') for item in lst]
类似于列表理解,但有点不同 这是映射功能
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.
类似于列表理解,但有点不同 这是映射功能
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.
其他答案不使用Store的newlist是的,OP可以选择重新定义lst。或者在函数中插入此代码,就像他在问题中所做的那样。其他答案不使用Store的newlist是的,OP可以选择重新定义lst。或者在函数中插入此代码,就像他在问题中所做的那样。