对于列表["foo", "bar", "baz"]和列表中的项目"bar",如何在Python中获取其索引(1)?
我正在寻找最快的方法来了解列表中是否存在值(列表中包含数百万个值)以及它的索引是什么?我知道列表中的所有值都是唯一的,就像我的例子一样.
我尝试的第一种方法是(在我的实际代码中为3.8秒):
a = [4,2,3,1,5,6]
if a.count(7) == 1:
b=a.index(7)
"Do something with variable b"
Run Code Online (Sandbox Code Playgroud)
我尝试的第二种方法是(快2倍:我的实际代码为1.9秒):
a = [4,2,3,1,5,6]
try:
b=a.index(7)
except ValueError:
"Do nothing"
else:
"Do something with variable b"
Run Code Online (Sandbox Code Playgroud)
Stackoverflow用户提出的方法(我的实际代码为2.74秒):
a = [4,2,3,1,5,6]
if 7 in a:
a.index(7)
Run Code Online (Sandbox Code Playgroud)
在我的实际代码中,第一种方法需要3.81秒,第二种方法需要1.88秒.这是一个很好的改进但是:
我是Python /脚本的初学者,我想知道是否有最快的方法可以做同样的事情并节省更多的处理时间?
我的应用程序更具体的解释:
在blender的API中,a可以访问粒子列表:
particles = [1, 2, 3, 4, etc.]
Run Code Online (Sandbox Code Playgroud)
从那里,我可以访问它的位置:
particles[x].location = [x,y,z]
Run Code Online (Sandbox Code Playgroud)
我通过搜索每个粒子的位置测试每个粒子是否存在邻居,如:
if [x+1,y,z] in particles.location
"Find the identity of this neighbour particle in x:the particle's index
in the array"
particles.index([x+1,y,z])
Run Code Online (Sandbox Code Playgroud) 我遇到过这个:
item = someSortOfSelection()
if item in myList:
doMySpecialFunction(item)
Run Code Online (Sandbox Code Playgroud)
但有时它不适用于我的所有项目,就好像它们在列表中未被识别一样(当它是一个字符串列表时).
这是在列表中找到一个项目的最"Python化"的方式:if x in l:?
如果我有一个字符串数组,我可以检查一个字符串是否在数组中而不进行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?
我想知道我们是否可以断言列表中的所有元素都不是None,因此 whilea = None会引发错误。
样本清单是[a, b, c]
我已经尝试过了,如果任何一个元素不是,assert [a, b, c] is not None它就会返回,但不会验证所有元素。你能帮忙想一下吗?谢谢!!TrueNone
我希望能够输入一个值并检查它是否在列表中,如果它在列表中运行,则运行所需的其余程序.
a=input('enter value')
b=(1,2,3,4)
c=(5,6,7,8,9)
if a is in b:
print 'enter in code thats wanted'
Run Code Online (Sandbox Code Playgroud) python ×7
list ×4
arrays ×1
assert ×1
contains ×1
find ×1
indexing ×1
performance ×1
python-2.7 ×1
set ×1