[英]Understanding the python code snippet
Please help me understand the following code snippet :- 请帮我理解以下代码片段: -
def any(l):
"whether any number is known from list l"
s = set(list(l)[0])
for x in l:
s.intersection_update(set(x))
return len(s) > 0
Here l is a list containing the list of 3-tuples eg [(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)] etc. In particular I am facing difficulty understanding the line 3 这里l是一个包含3元组列表的列表,例如[(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10) ,5),(23,11,2),(25,5,2)]等。特别是我在理解第3行时遇到困难
s=set(list(l)[0])
set(list(l)[0])
list(l)
creates a new list from l
and then [0]
is to fetch its first item, which is (17,14,13)
. list(l)
从l
创建一个新列表,然后[0]
获取它的第一个项目,即(17,14,13)
。 and then set((17,14,13))
returns a set of this tuple. 然后
set((17,14,13))
返回一组这个元组。 set is a data structure which contains only unique hash-able elements. set是一个只包含唯一可散列元素的数据结构。 ie
set((10,12,10))
equals {10,12}
即
set((10,12,10))
等于{10,12}
>>> l=[(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)]
>>> list(l)[0]
(17, 14, 13)
>>> set(list(l)[0])
{17, 13, 14}
In s=set(list(l)[0])
, you're creating a set from the first element of the list. 在
s=set(list(l)[0])
,您将从列表的第一个元素创建一个集合。 In your case, you could have used set(l[0])
and it would do the same thing. 在你的情况下,你可以使用
set(l[0])
,它会做同样的事情。 Essentially, you're creating a set based on the first tuple of the list. 基本上,您正在基于列表的第一个元组创建一个集合。 Overall, your function is trying to find if there is any common element(number) between all tuples.
总的来说,您的函数正在尝试查找所有元组之间是否存在任何公共元素(数字)。
A set
is a python collection of hashable-types that has the special feature that no entity in the collection can repeat (the hash returned from it's __hash__
magic method, and thereby also the boolean return from the __eq__
method cannot be equal to any other entity in the list) It is used wherever a collection is required that can not have repeated entities. set
是hashable-types的python集合,具有特殊功能,集合中的任何实体都不能重复(从它的__hash__
魔术方法返回的散列,因此__eq__
方法的布尔返回也不能等于任何其他实体在列表中)它用于需要不能重复实体的集合的任何地方。
It's hard to tell the intention of the snippet entirely without knowing the context of its use, especially since the values you have for l are all tuples within a container list. 在不知道其使用的上下文的情况下,很难完全分辨出代码片段的用意,特别是因为你拥有的值是容器列表中的所有元组。 The
intersection_update
is a method of a set that returns a set from the original keeping only elements also found in the one that is passed as an argument. intersection_update
是一个集合的方法,它从原始集合中返回一个集合,仅保留在作为参数传递的元素中找到的元素。 The zero-indexed key is fetching the first tuple from the list. 零索引键从列表中获取第一个元组。
http://docs.python.org/library/sets.html http://docs.python.org/library/sets.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.