我看到人们正在使用any收集另一个列表来查看列表中是否存在某个项目,但是有一个快速的方法可以做到吗?:
if list.contains(myItem):
# do something
Run Code Online (Sandbox Code Playgroud) 如果我有一个字符串数组,我可以检查一个字符串是否在数组中而不进行for循环?具体来说,我正在寻找一种方法在一个if语句中这样做,所以像这样:
if [check that item is in array]:
Run Code Online (Sandbox Code Playgroud) 假设我有一个ints 列表:
listOfNumbers = range(100)
Run Code Online (Sandbox Code Playgroud)
我想返回符合某种条件的元素列表,比如说:
def meetsCondition(element):
return bool(element != 0 and element % 7 == 0)
Run Code Online (Sandbox Code Playgroud)
什么是Python化的方式返回子list在一个元素list为这 meetsCondition(element)是True?
一种天真的方法:
def subList(inputList):
outputList = []
for element in inputList:
if meetsCondition(element):
outputList.append(element)
return outputList
divisibleBySeven = subList(listOfNumbers)
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以做到这一点,也许有一个列表理解或set()函数,没有临时的outputList?
有关在数字列表中检索部分匹配项的方法,请访问:
但是,如果您正在寻找如何检索字符串列表的部分匹配项,您会在下面的答案中找到简明扼要地解释的最佳方法。
SO:部分匹配的 Python 列表查找显示了如何返回 a bool,如果 alist包含部分匹配(例如begins,ends, 或contains)某个字符串的元素。但是你怎么能返回元素本身,而不是True或False
l = ['ones', 'twos', 'threes']
wanted = 'three'
Run Code Online (Sandbox Code Playgroud)
在这里,链接问题中的方法将返回True使用:
any(s.startswith(wanted) for s in l)
Run Code Online (Sandbox Code Playgroud)
那么如何返回元素'threes'呢?
我有一些像这样的列表:
lines = [
"line",
"subline2",
"subline4",
"line",
]
Run Code Online (Sandbox Code Playgroud)
我想获取以某些子字符串开头的行索引列表.
我用这种方法:
starts = [n for n, l in enumerate(lines) if l.startswith('sub')]
Run Code Online (Sandbox Code Playgroud)
但也许有人知道更美丽的方法吗?
在我的代码中,我曾经if a == b or a == c or a == d:经常进行比较。在某些时候,我发现这些可以很容易地缩短为if a in {b, c, d}:或者if a in (b, c, d):如果值不可哈希。但是,我从未在其他任何人的代码中看到过这样的结构。这可能是因为:
==方法比较慢。==方法是更Python。in除了我,没有人想过办法。如果有,是哪个原因?
是否有内置的python等效std::find_if于查找给定条件的列表的第一个元素true?换句话说,类似于index()列表的功能,但具有任意的一元谓词,而不仅仅是对相等性的测试.
我不想使用列表理解,因为我想到的特定谓词计算起来有些昂贵.
如果我想查找x是否等于列表中的任何对象,我们如何在python中执行此操作?
就像是
if x == list[any]:
do something
Run Code Online (Sandbox Code Playgroud) 对不起,我是python的初学者.我想要做的是查看项目所在的列表.我所拥有的是一些列表设置如下:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
Run Code Online (Sandbox Code Playgroud)
让我们说我想找到项目5所在的列表.我目前正在做的是:
if l1.index(5)!=False:
print 1
elif l2.index(5)!=False:
print 2
elif l3.index(5)!=False:
print 3
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我该怎么做?
我有一本字典,每个键都有很多值。如何从该键打印特定值?
例如,我的键是“CHMI”,但它有 14 个与之关联的值。如何仅打印CHMI: 48680值?
CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680', '17.26', '12.6', '1.96', '12.24', '14.04', '23.15']
Run Code Online (Sandbox Code Playgroud) python ×10
list ×3
contains ×2
arrays ×1
collections ×1
dictionary ×1
filter ×1
python-2.7 ×1
search ×1
set ×1
string ×1
syntax ×1