2015-07-01 96 views
-3

我遇到了這些結構,我不太確定他們做了什麼。有人可以解釋嗎?什麼是一組? 「我在我身上」是做什麼的?

setx = set([a for a in i])  
sety = set([y for y in j]) 

代碼,用於上下文

a = int(input()) 
for i in range(a): 
    i = (input()) 
    j = (input()) 
    setx = set([a for a in i])  
    sety = set([y for y in j]) 
    if setx.intersection(sety) == set(): 
     print("NO") 
    else: 
     print("YES") 
+2

你怎麼看它? – Akavall

+0

https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions – IanAuld

+0

請修正您的縮進 – heinst

回答

2

[a for a in i]list comprehension。這基本上是一個簡潔的方式來做一個清單。

它們可能非常有用,或者它們可能是很多不可讀代碼的來源,或者兩者兼而有之。完整的語法

[f(i) for i in iterator if conditional(i)] 

例子:

廣場的名單:[i**2 for i in range(n)]

5平方不能整除的名單:[i**2 for i in range(n) if i**2 % 5 =! 0]

至於設置Set是一個非常python中有用的數據類型。這基本上是一個沒有價值的字典。所有元素必須是唯一且可散列的,並且集合不存儲順序,但檢查以查看對象是否在集合中不取決於集合的長度。

在這種情況下,您的代碼可能使用集合來確定兩個輸入是否共享任何共同點更快更容易編寫。我也不知道你的代碼是幹什麼的,但我可以肯定它不是它想要的,如果我要重寫它,它會是這樣的

a = int(input()) 
setx = set() #initializing empty sets 
sety = set() 
for _ in range(a): #underscore often used when you don't care about what you're iterating over, just that you iterate a certain amount of times. 
    setx.add(input()) #Previously, you'd just get the last input 
    sety.add(input()) #I doubt that's what you wanted 
if setx.intersection(sety): #no need to compare to empty set. if set() will evaluate as false 
    print("NO") 
else: 
    print("YES") 

相關問題