[英]Using list comprehension to reduce a function that transforms list of lists in tuples of tuples
i want to change this function using a list comprehension in order that it will have 1 or to lines. 我想使用列表理解来更改此功能,以使其具有1或行。 the function transfor a list containing list in a tuple containing tupples inside
该函数将一个列表转换为一个列表,该列表包含一个内部包含tupples的元组
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
. 对上述列表理解的更明确的解释是,将
lista
中所有元素的tuple
创建为tuple
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. 您在这里不需要索引,因为
lst in lista
直接对元素进行迭代。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.