用list& c反转字典 [英] invert dictionary with list &c
问题描述
最近我发现自己使用一种模式来制作新的词典
,我的意思是两次:
def invert(d):
nd = {}
[nd.setdefault(val,[])。附加(键)表示k,v表示d]
返回
def count(l):
d = {}
[d.setdefault(w,0)+ = 1 for w in l]
返回d
这是做这类事情的pythonic方法吗?理想情况下我想把它们写成一个衬里,但是我看不出怎么样。
Des
-
" [T]语言学的结构趋势扎根于
二十年代和三十年代初的国际大会[...] />
与胡塞尔语中的现象学关系密切且有效连接
和黑格尔版本。 - Roman Jakobson
Lately I have found myself using a pattern to make new dictionaries
quite often, by which I mean twice:
def invert(d):
nd = {}
[nd.setdefault(val, []).append(key) for k, v in d]
return nd
def count(l):
d = {}
[d.setdefault(w, 0) += 1 for w in l]
return d
Is this the pythonic way to do such things? Ideally I''d like to write
them as one liners, but I can''t see how.
Des
--
"[T]he structural trend in linguistics which took root with the
International Congresses of the twenties and early thirties [...] had
close and effective connections with phenomenology in its Husserlian
and Hegelian versions." -- Roman Jakobson
推荐答案
Des Small写道:
Des Small wrote:
最近我发现自己使用了一个模式来经常制作新的词典,我的意思是两次:
def invert(d):
nd = {}
[nd.setdefault(val,[ ])。附加(键)表示k,v表示d]
返回nd
def count(l):
d = {}
[d.setdefault (w,0)+ = 1 for w in l]
返回d
这是做这类事情的pythonic方法吗?理想情况下我想把它们写成一个衬垫,但我看不出如何。
Des
Lately I have found myself using a pattern to make new dictionaries
quite often, by which I mean twice:
def invert(d):
nd = {}
[nd.setdefault(val, []).append(key) for k, v in d]
return nd
def count(l):
d = {}
[d.setdefault(w, 0) += 1 for w in l]
return d
Is this the pythonic way to do such things? Ideally I''d like to write
them as one liners, but I can''t see how.
Des
大多数pythonic方式恕我直言:
def invert(d):
nd = {}
for k,v in d.iteritems():
nd [v] = nd.get(k,[])+ [k]
return nd
def count(l):
d = {}
for e in l:
d [e] = d.get (e,0)+ 1
返回d
或者用默认值定义dict:
import复制
class defdict(dict):
def __init __(self,default = None):
self._default = default
super(dict,self).__ init __(self)
def __getitem __(self,k):
返回自我。获取(k,copy.deepcopy(self._default))#或setdefault
def invert(d):
nd = defdict([])
代表k,v代表d.iteritems():
nd [v] + = [k]
返回nd
def count(l):
d = defdict(0)
for e in l:
d [e] + = 1
返回d
但是,如果你坚持单行,我可以建议一些;):
def count(l ):
返回减少(
lambda d,e :( d.update(dict([(e,d.get(e,0)+ 1)]) ),d)[1],
l,{}
)
def invert(d):
return reduce(
lambda d,(k,v):( d.update(dict([(v,d.get(v,[])+ [k])] )),d)[1],
d.iteritems(),{}
)
(以几个给出)线条,但可以写成一个)
甚至
count = lambda l:reduce(
lambda d,e:(d.update(dict([(e,d.get(e,0)+ 1)])),d)[1],
l,{}
)
:)
问候,
anton。
Most pythonic way IMHO would be:
def invert(d):
nd = {}
for k, v in d.iteritems():
nd[v] = nd.get(k, []) + [k]
return nd
def count(l):
d = {}
for e in l:
d[e] = d.get(e, 0) + 1
return d
Or to define dict with default values:
import copy
class defdict(dict):
def __init__(self, default = None):
self._default = default
super(dict, self).__init__(self)
def __getitem__(self, k):
return self.get(k, copy.deepcopy(self._default)) # or setdefault
when
def invert(d):
nd = defdict([])
for k, v in d.iteritems():
nd[v] += [k]
return nd
def count(l):
d = defdict(0)
for e in l:
d[e] += 1
return d
However, if you insist on one-liners, I can suggest some ;):
def count(l):
return reduce(
lambda d, e: (d.update(dict([(e, d.get(e, 0) + 1)])), d)[1],
l, {}
)
def invert(d):
return reduce(
lambda d, (k, v): (d.update(dict([(v, d.get(v, []) + [k])])), d)[1],
d.iteritems(), {}
)
(given in several lines, but can be written in one)
or even
count = lambda l: reduce(
lambda d, e: (d.update(dict([(e, d.get(e, 0) + 1)])), d)[1],
l, {}
)
:)
regards,
anton.
在文章< yy ************** @ pc156.maths.bris.ac.uk> ;,
Des小< de ******* @ bristol.ac.uk>写道:
In article <yy**************@pc156.maths.bris.ac.uk>,
Des Small <de*******@bristol.ac.uk> wrote:
最近我发现自己经常使用一种模式制作新的词典
,我的意思是两次:
def invert(d):
nd = {}
[nd.setdefault(val,[])。附加(键)表示k,v表示d]
返回nd
def count( l):
d = {}
[d.setdefault(w,0)+ = 1 for w in l]
返回d
这是pythonic做这种事的方式?理想情况下我想把它们写成一个衬里,但我看不出怎么样。
Lately I have found myself using a pattern to make new dictionaries
quite often, by which I mean twice:
def invert(d):
nd = {}
[nd.setdefault(val, []).append(key) for k, v in d]
return nd
def count(l):
d = {}
[d.setdefault(w, 0) += 1 for w in l]
return d
Is this the pythonic way to do such things? Ideally I''d like to write
them as one liners, but I can''t see how.
一旦你写完了以上内容,他们是单行:
inverted_dict = invert(some_dict)
为什么你需要更少?任何
读者都不会怀疑翻译字典真的是你正在做的事情。在没有任何人注意的情况下,很少有机会在一个错误的情况下偷偷摸摸地搞砸了这个过程。
问候。 Mel。
Once you''ve written the above, they are one-liners:
inverted_dict = invert (some_dict)
Why would you need less? There''s little doubt in any
reader''s mind that inverting a dictionary is really what
you''re doing; there''s little chance of a typo sneaking in
and messing up the process without anybody noticing, etc.
Regards. Mel.
>>>>> "德" == Des Small< de ******* @ bristol.ac.uk>写道:
def count(l):
d = {}
[d.setdefault(w,0)+ = 1 for w in l]
返回d
此代码引发SyntaxError。
标准惯用语使用
字典计算列表中的所有元素是
def count(l):
d = {}
for w in l:d [w] = d.get(w,0)+ 1
返回d
我认为基本的经验法则是使用setdefault方法来获取
可变对象(list,dict)和不可变
元素的获取方法(字符串,整数,浮点数,元组) )。
此外,很多人会发现使用列表推导而忽略了他们的返回值,就像你在''[d.setdefault(w, 0)+ = 1 for w in
l]''滥用列表组合。至少我已经被告诫过这样做了,所以我现在必须告诫你继续玩b / b
暴力循环。
Des>这是做这类事情的pythonic方式吗?理想情况下我想要
Des>把它们写成一个衬里,但我看不出怎么样。
我认为争取单行是不是pythonic。大多数python
编码器重视紧凑性的可读性。更重要的是,
编写一个适当命名的函数,该函数可以工作并且可读,并且比编写单行代码更有效。
John Hunter
>>>>> "Des" == Des Small <de*******@bristol.ac.uk> writes:
def count(l):
d = {}
[d.setdefault(w, 0) += 1 for w in l]
return d
This code raises a SyntaxError.
The standard idiom for counting all the elements in a list with a
dictionary is
def count(l):
d = {}
for w in l: d[w] = d.get(w,0) + 1
return d
I think the basic rule of thumb is to use the setdefault approach for
mutable objects (list, dict) and the get approach for immutable
elements (strings, ints, floats, tuples).
Also, many here would find using list comprehensions while ignoring
their return value, as you did in ''[d.setdefault(w, 0) += 1 for w in
l]'' to be an abuse of list comps. At least I''ve been admonished for
doing so, and so I must now admonish you to continue the cycle of
violence.
Des> Is this the pythonic way to do such things? Ideally I''d like
Des> to write them as one liners, but I can''t see how.
I think that striving for one-liners is not pythonic. Most python
coders value readability over compactness. It''s more important to
write an appropriately named function that works and is readable and
efficient than it is to write a one liner.
John Hunter
这篇关于用list& c反转字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!