我正在寻找最快的方法来了解列表中是否存在值(列表中包含数百万个值)以及它的索引是什么?我知道列表中的所有值都是唯一的,就像我的例子一样.
我尝试的第一种方法是(在我的实际代码中为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) 我有一个清单:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
Run Code Online (Sandbox Code Playgroud)
并希望搜索包含该字符串的项目'abc'.我怎样才能做到这一点?
if 'abc' in my_list:
Run Code Online (Sandbox Code Playgroud)
会检查是否'abc'存在在列表中,但它的一部分'abc-123'和'abc-456','abc'对自己不存在.那么如何获得包含的所有项目'abc'?
我遇到过这个:
item = someSortOfSelection()
if item in myList:
doMySpecialFunction(item)
Run Code Online (Sandbox Code Playgroud)
但有时它不适用于我的所有项目,就好像它们在列表中未被识别一样(当它是一个字符串列表时).
这是在列表中找到一个项目的最"Python化"的方式:if x in l:?
我看到人们正在使用any收集另一个列表来查看列表中是否存在某个项目,但是有一个快速的方法可以做到吗?:
if list.contains(myItem):
# do something
Run Code Online (Sandbox Code Playgroud) 我想dict在python中制作一个深层副本.不幸的是,该.deepcopy()方法不存在dict.我怎么做?
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = my_dict.deepcopy()
Traceback (most recent calll last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'deepcopy'
>>> my_copy = my_dict.copy()
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
7
Run Code Online (Sandbox Code Playgroud)
最后一行应该是3.
我希望这些修改my_dict不会影响快照my_copy.
我怎么做?该解决方案应与Python 3.x兼容.