i want to change this function using a list comprehension in order that it will have 1 or to lines. the function transfor a list containing list in a tuple containing tupples inside
def lol(lista):
novotuplo = ()
for i in range(len(lista)):
novotuplo += (tuple(lista[i]),)
return novotuplo
This should work:
lista = [[1,2], [3,4], [5,6]]
print(tuple(tuple(i) for i in lista))
# ((1, 2), (3, 4), (5, 6))
A more explicit explanation of the above list comprehension would be create a tuple
of all elements in lista
converted to tuple
.
我认为应该这样做。
novotuplo = tuple(tuple(item) for item in lista)
If you want it in a functional form, this is one way. You do not need an index here because lst in lista
iterates over the elements directly.
lista = [[1],[2],[3]]
def lol(lista):
novotuplo = tuple(tuple(lst) for lst in lista)
return novotuplo
print (lol(lista))
# ((1,), (2,), (3,))
您可以将项目map
到tuple()
构造函数:
tuple(map(tuple, lista))
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.