I have a function to process the list of tuples. What is the easiest way to include for
loop inside the function itself? I am fairly new to python, trying to convert this in OOP function. Any help will be appreciated.
My current solution:
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))
output will be
[(c,d),(m,n),(h,j)]
just write your loop in func
:
tups = [(1,a),(2,b),(5,t)]
def func(tuples):
for a, b in tuples:
# do something for a and b
result.append((c,d))
return result
output = []
output.append(func(tups))
I think map
is more suitable for your use case
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)
Output:
[('a', 1), ('b', 2), ('t', 5)]
Just do this with list comprehensions:
tups = [(1,"a"),(2,"b"),(5,"t")]
print([(obj[1], obj[0]) for obj in tups])
# [('a', 1), ('b', 2), ('t', 5)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.