2013-01-03 24 views
0

我是比較新的蟒蛇和想要做的事,如:如果值x ==列表Ÿ任何值:蟒蛇

if value x == any value in list y: 
    write x 

這將wihtin的功能操作,所以只有符合特定哪些解決方案標準將寫入csv,因爲它們會生成

+3

'如果x在MYLIST: ' – joaquin

回答

7
>>> x = 8 
>>> if x in (1, 2, 3, 5, 8, 13, 21, 34, 55): 
     print('x is an early Fibonacci number') 
x is an early Fibonacci number 
+0

乾杯! – user1665220

1

這會適合您嗎?

x = somevalue 
y = somelist 
if x in y: 
    print x #not sure if this is what you mean by 'write' 
4

您可以使用的語法:

if x in ["a", "b", "c"] 
    ... do stuff 

而且,如果你還在乎的X,你可以使用數出現的次數:

if y.count(x) == 1 
    ... do stuff 
+0

用於提及'count'的+1 – Don

+1

@Don如果您只對列表中某個項目的存在感興趣,count將會變慢,因爲它需要遍歷每個* list項目。 – poke

+0

@poke這就是爲什麼我說'in'是更好的選擇,但是如果你需要實際使用的次數,你也應該提一提。 –