我喜欢Python列表理解语法.
它也可以用来创建字典吗?例如,通过迭代成对的键和值:
mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work
python dictionary list-comprehension dictionary-comprehension
想象一下,你有:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
生成以下字典的最简单方法是什么?
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
有没有办法将Python元组扩展为函数 - 作为实际参数?
例如,这里expand()有魔力:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
我知道可以定义myfun为myfun((a, b, c)),但当然可能有遗留代码.谢谢
我需要在列表中找到元素的频率
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
输出 - >
b = [4,4,2,1,2]
另外我想从a中删除重复项
a = [1,2,3,4,5]
有很多方法可以编写计算直方图的Python程序.
通过直方图,我的意思是一个函数,它计算a中对象的出现次数iterable并输出字典中的计数.例如:
>>> L = 'abracadabra'
>>> histogram(L)
{'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2}
编写此函数的一种方法是:
def histogram(L):
    d = {}
    for x in L:
        if x in d:
            d[x] += 1
        else:
            d[x] = 1
    return d
是否有更简洁的方法来编写此功能?
如果我们在Python中有字典理解,我们可以写:
>>> { x: L.count(x) for x in set(L) }
但由于Python 2.6没有它们,我们必须写:
>>> dict([(x, L.count(x)) for x in set(L)])
虽然这种方法可以读取,但效率不高:L经过多次.此外,这对单寿命发电机不起作用; 该函数应该对迭代器生成器同样有效,例如:
def gen(L):
    for x in L:
        yield x
我们可能会尝试使用该reduce函数(RIP):
>>> reduce(lambda d,x: dict(d, …我是Python的新手.我试图找到一种简单的方法来计算列表中重复的元素数量,例如
MyList = ["a", "b", "a", "c", "c", "a", "c"]
输出:
a: 3
b: 1
c: 3
['a','a','b','c','c','c']
至
[2, 2, 1, 3, 3, 3]
和
{'a': 2, 'c': 3, 'b': 1}
当我尝试从字典中获取值时,我想知道处理键盘错误的最佳方法。
我需要这个,因为我的字典包含一些事件的计数。每当发生事件时,我都会从dict中获取计数并对其进行递增并放回原位。
我在网上找到了一些解决方案,但它们适用于其他一些语言。任何帮助表示赞赏。
我现在正在处理keyerror异常。想知道处理字典中键错误的最佳方法。
注意:这不是关于计数列表中的项目,而是关于从dict检索值(不存在)时处理异常。
我想从文本文件中获取每个单词,并在字典中计算单词频率.
例: 'this is the textfile, and it is used to take words and count'
d = {'this': 1, 'is': 2, 'the': 1, ...} 
我不是那么远,但我只是看不出如何完成它.我的代码到目前为止:
import sys
argv = sys.argv[1]
data = open(argv)
words = data.read()
data.close()
wordfreq = {}
for i in words:
    #there should be a counter and somehow it must fill the dict.