我喜欢Python列表理解语法.
它也可以用来创建字典吗?例如,通过迭代成对的键和值:
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work
Run Code Online (Sandbox Code Playgroud) python dictionary list-comprehension dictionary-comprehension
想象一下,你有:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
Run Code Online (Sandbox Code Playgroud)
生成以下字典的最简单方法是什么?
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
Run Code Online (Sandbox Code Playgroud) 我想获取两个列表并找到两者中出现的值.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
Run Code Online (Sandbox Code Playgroud)
[5]例如,会回来.
我理解的是什么timeit,但我不知道如何在我的代码中实现它.
我如何比较两个功能,说insertion_sort和tim_sort,用timeit?
什么是Pythonic方法来实现以下目标?
# Original lists:
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
# List of tuples from 'list_a' and 'list_b':
list_c = [(1,5), (2,6), (3,7), (4,8)]
Run Code Online (Sandbox Code Playgroud)
每个成员list_c都是一个元组,其第一个成员来自list_a,而第二个来自list_b.
我有纬度列表和经度列表,需要迭代纬度和经度对.
是否更好:
A.假设列表长度相等:
for i in range(len(Latitudes)):
Lat,Long=(Latitudes[i],Longitudes[i])
Run Code Online (Sandbox Code Playgroud)B.或者:
for Lat,Long in [(x,y) for x in Latitudes for y in Longitudes]:
Run Code Online (Sandbox Code Playgroud)(注意B是不正确的.这给了我所有的对,相当于itertools.product())
关于每个的相对优点的任何想法,或者更多的pythonic?
我想执行元素明智的乘法,在Python中将两个列表乘以值,就像我们可以在Matlab中一样.
这就是我在Matlab中的表现.
a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]
Run Code Online (Sandbox Code Playgroud)
对于from 和from的每个组合x * y,列表理解将给出16个列表条目.不确定如何映射这个.xayb
如果有人对此感兴趣,我有一个数据集,并希望将其乘以Numpy.linspace(1.0, 0.5, num=len(dataset)) =).
如何在同一个for循环中包含两个变量?
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
...
Run Code Online (Sandbox Code Playgroud) 想想我正在调用它的副作用的函数,而不是返回值(比如打印到屏幕,更新GUI,打印到文件等).
def fun_with_side_effects(x):
...side effects...
return y
Run Code Online (Sandbox Code Playgroud)
现在,是Pythonic使用列表推导来调用这个函数:
[fun_with_side_effects(x) for x in y if (...conditions...)]
Run Code Online (Sandbox Code Playgroud)
请注意,我不会将列表保存在任何位置
或者我应该像这样调用这个函数:
for x in y:
if (...conditions...):
fun_with_side_effects(x)
Run Code Online (Sandbox Code Playgroud)
哪个更好?为什么?
假设我有两个或更多相同长度的列表.迭代它们的好方法是什么?
a,b是名单.
for i, ele in enumerate(a):
print ele, b[i]
Run Code Online (Sandbox Code Playgroud)
要么
for i in range(len(a)):
print a[i], b[i]
Run Code Online (Sandbox Code Playgroud)
或者我缺少任何变种?
使用一个优于其他优势是否有任何特别的优势?
python ×10
list ×5
dictionary ×2
for-loop ×1
iteration ×1
merge ×1
multiplying ×1
time ×1
timeit ×1
tuples ×1