简体   繁体   English

使用map和lambda的python字典赋值

[英]python dictionary assignment using map and lambda

I was just curious to know if the following loop is doable with the map() rather than using for loop ? 我只是想知道以下循环是否可以使用map()而不是使用for循环? If yes please be kind enough to show how ? 如果是,请善待展示如何? or what's the most efficient way to do the following ? 或者最有效的方法是什么?

f = open('sample_list.txt').read().split('\n')

val =   lambda x: re.match('[a-zA-z0-9]+',x).group() if x else None

for line in f:
    if line.find('XYZ') == -1:
        dict[val(line)]=0
    else:
        dict[val(line)]=1

This program reads a file formatted as : 该程序读取格式为:

ABCD XYZ 
DEFG ABC

then creates a dicionary with first word as KEY and if the second value is XYZ then it will assign a value of 1 else 0. 然后创建一个第一个单词作为KEY的dicionary,如果第二个值是XYZ,那么它将赋值1 else 0。

ie dict will be : 即dict将是:

{'ABCD': 1, 'DEFG': 0}

UPDATE : 更新:

I timed the approaches suggested by @shx2 and @arekolek dictionary comprehension is faster, and @arekolek's approach is way faster than anything as it doesn't use the val() lambda function i declared. 我定时了@shx2@arekolek字典理解建议的方法更快, @ arekolek的方法比任何东西都快,因为它不使用我声明的val()lambda函数。

the code : 代码 :

def a():
    return {
    val(line) : 0 if line.find('XYZ') == -1 else 1
    for line in f
    }

def b():
    return dict(map(lambda x: (x[0], int(x[1] == 'XYZ')), map(str.split, f)))

def c():
    return {k: int(v == 'XYZ') for k, v in map(str.split, f)}

print 'a='+timeit.timeit(a)
print 'b='+timeit.timeit(b)
print 'c='+timeit.timeit(c)

result : 结果:

a = 13.7737597283
b = 6.82668938135
c = 3.98859187269

Thanks both for showing this :) 谢谢你们两个展示:)

Better to use dict comprehension than map . 最好使用dict理解而不是map

Can be done like this: 可以这样做:

my_dict = {
    val(line) : 0 if line.find('XYZ') == -1 else 1
    for line in f
}

Some notes and improvements: 一些注意事项和改进:

  1. dict is not a good variable name in python dict在python中不是一个好的变量名
  2. Alternatives to the complicated expression 0 if line.find('XYZ') == -1 else 1 : 0 if line.find('XYZ') == -1 else 1 ,则复杂表达式0 if line.find('XYZ') == -1 else 1替代方法0 if line.find('XYZ') == -1 else 1
    • int(line.find('XYZ') != -1) (converting bool to int ) int(line.find('XYZ') != -1) (将bool转换为int
    • if you can leave the values as bool s: line.find('XYZ') != -1 如果你可以将值保留为bool s: line.find('XYZ') != -1
    • 'XYZ' in line (credit: @JonClements) 'XYZ' in line (信用:@JonClements)

With a lambda: 用lambda:

dict(map(lambda x: (x[0], int(x[1] == 'XYZ')), map(str.split, f)))

Or: 要么:

dict(map(lambda k, v: (k, int(v == 'XYZ')), *map(str.split, f)))

Dictionary comprehension: 字典理解:

{k: int(v == 'XYZ') for k, v in map(str.split, f)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM