Python 在处理元组列表的函数中包含For循环
我有一个处理元组列表的函数。在函数本身中包含Python 在处理元组列表的函数中包含For循环,python,python-3.x,Python,Python 3.x,我有一个处理元组列表的函数。在函数本身中包含for循环的最简单方法是什么?我是python新手,尝试在OOP函数中转换它。任何帮助都将不胜感激 我当前的解决方案: tups = [(1,a),(2,b),(5,t)] def func(a,b): # do something for a and b return (c,d) output = [] for x, y in tups: output.append(func(x,y)) 输出将是 [(c,d),(m,n
for
循环的最简单方法是什么?我是python新手,尝试在OOP函数中转换它。任何帮助都将不胜感激
我当前的解决方案:
tups = [(1,a),(2,b),(5,t)]
def func(a,b):
# do something for a and b
return (c,d)
output = []
for x, y in tups:
output.append(func(x,y))
输出将是
[(c,d),(m,n),(h,j)]
只需在
func
中编写循环:
tups=[(1,a)、(2,b)、(5,t)]
def func(元组):
对于元组中的a、b:
#为a和b做点什么
结果.追加((c,d))
返回结果
输出=[]
output.append(func(tups))
我认为map
更适合您的用例
tups = [(1,"a"),(2,"b"),(5,"t")]
def func(z):
# some random operation say interchanging elements
x, y = z
return y, x
tups_new = list(map(func, tups))
print(tups_new)
输出:
[('a', 1), ('b', 2), ('t', 5)]
只需使用列表理解即可:
tups = [(1,"a"),(2,"b"),(5,"t")]
print([(obj[1], obj[0]) for obj in tups])
# [('a', 1), ('b', 2), ('t', 5)]
到底是什么问题?在函数本身中包含for循环的最简单方法是什么?你是在问如何编写for循环吗?这很快也很简单。谢谢