有没有办法编写一个If可以有多个参数的(或等效的)语句,如果其中任何一个满足逻辑,那么使用该变量?
例如
if len(x) == 1 or len(y) == 1 or len(z) == 1 or ... len(zz) == 1:
# do something with the variable that met the condition
Run Code Online (Sandbox Code Playgroud)
所以说只有z长度1,我可以用第一个True答案并使用它的方式写出上面的想法/公式吗?
所以像
x = "123"
y = "234"
z = "2"
xx = "1234"
yy = "12345"
if len(x) == 1 or len(y) == 1 or len(z) == 1 or len(xx) == 1 or len(yy) == 1:
#do something with the …Run Code Online (Sandbox Code Playgroud) 我有以下清单:
search_list = ['STEEL','IRON','GOLD','SILVER']
Run Code Online (Sandbox Code Playgroud)
我需要在数据框(df)中进行搜索:
a b
0 123 'Blah Blah Steel'
1 456 'Blah Blah Blah'
2 789 'Blah Blah Gold'
Run Code Online (Sandbox Code Playgroud)
并将匹配的行插入新的数据帧(newdf),并从列表中添加带有匹配词的新列:
a b c
0 123 'Blah Blah Steel' 'STEEL'
1 789 'Blah Blah Gold' 'GOLD'
Run Code Online (Sandbox Code Playgroud)
我可以使用以下代码提取匹配的行:
newdf=df[df['b'].str.upper().str.contains('|'.join(search_list),na=False)]
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将列表中的匹配词添加到c列中。
我在想匹配必须以某种方式捕获列表中匹配单词的索引,然后使用索引号提取值,但是我不知道该怎么做。
任何帮助或指针将不胜感激
谢谢
我该如何抓住以下内容:
l=[None, None, 'hello', 'hello']
first(l) ==> 'hello'
l = [None, None, None, None]
first(l) ==> None
Run Code Online (Sandbox Code Playgroud)
我可以尝试使用列表理解,但如果它没有项目则会出错.
我有一个数字数组,例如“ 17.2、19.1、20.4、47.5、34.2、20.1、19”
试图找出一种方法来选择第一个数字超过20(并且没有一个跟随),最后一个数字超过20,然后再降至低于20。
到目前为止,我只尝试选择20到23之间的数字,但这并不理想(例如,请参见代码)
nums = [15, 16.2, 17.1, 19.7, 20.2, 21.3, 46.2, 33.7, 27.3, 21.2, 20.1, 19.6]
test_lst = [x for x in nums if x >=20 and x<=23]
print test_lst
Run Code Online (Sandbox Code Playgroud)
输出与预期的一样,但我想仅获得第一个和最后一个超过20的数字,而没有其余的数字。我意识到这对于大多数新手来说可能微不足道