Dict to“flat” (键,值)列表 [英] Dict to "flat" list of (key,value)

查看:88
本文介绍了Dict to“flat” (键,值)列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




如果答案很简单,请原谅我,但是你能不能告诉我如何实现

以下内容:


{k1:[v1,v2],k2:v3,...} - > [[k1,v1],[k1,v2],[k2,v3],...]


微妙的一点(至少对我而言)是扁平化。值列表。


提前致谢,

Nicolas


---- ==发表于Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News == ----
http:/ /www.newsfeed.com 世界排名第一的新闻组服务! > 100,000新闻组

--- = 19东/西海岸专业服务器 - 通过加密的总隐私= ---

Hi,

Forgive me if the answer is trivial, but could you tell me how to achieve
the following:

{k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...]

The subtle point (at least to me) is to "flatten" values that are lists.

Thanks in advance,
Nicolas

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---

推荐答案

2003年7月30日星期三21:26:19 +0200,Nicolas Girard< Ni ******************* @ removethis.nerim.net>写道:
On Wed, 30 Jul 2003 21:26:19 +0200, Nicolas Girard <Ni*******************@removethis.nerim.net> wrote:


如果答案很简单,请原谅我,但是你能否告诉我如何实现以下目标:
{k1:[v1,v2],k2:v3,...} - > [[k1,v1],[k1,v2],[k2,v3],...]

微妙的一点(至少对我而言)是扁平化。作为列表的值。
Hi,

Forgive me if the answer is trivial, but could you tell me how to achieve
the following:

{k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...]

The subtle point (at least to me) is to "flatten" values that are lists.



假设v3和其他类似的人不能引用列表

(或者你怎么能从格式中告诉它k1'的清单?):


(我引用你的名字以避免单独定义它们)


Assuming v3 and others like it can''t be references to lists
(or how could you tell it from the format of k1''s list?):

(I quoted your names to avoid haing to define them separately)

d = {''k1'':[''v1'',''v2''],''k2'':''v3''}
flat = []
for k,v in d.items():
... if isinstance(v,list):

... for v2 in v:

... flat.append([k,v2])

...其他:

... flat.append([ k,v])

... flat
[[''k2'',''v3''],[''k1'',''v1''], [''k1'',''v2'']]


或者您更喜欢难以置信的单行;-)


请注意,d.items(),

无法保证任何特定订单,但您可以排序下摆:

d = {''k1'':[''v1'',''v2''],''k2'':''v3''}
flat = []
items = d.items()
items.sort()#on keys
for k,v in items:
... if isinstance(v,list) :

#请注意,v是此处的列表,但确实存在您可能要保留的预先存在的订单。

#如果您想保证v2的排序输出不过,你可以在这里使用
#do v.sort(),虽然你可能会对其他人持有参考资料感到惊讶

#这些列表,因为他们会看到排序。为避免这种情况,请先复制一份,例如,

#v = v [:]; v.sort()#(未经测试,但我认为它应该可以工作;-)


... for v2 in v:

... flat .append([k,v2])

...其他:

... flat.append([k,v])

... flat
d = {''k1'':[''v1'',''v2''],''k2'':''v3''}
flat = []
for k,v in d.items(): ... if isinstance(v,list):
... for v2 in v:
... flat.append([k,v2])
... else:
... flat.append([k,v])
... flat [[''k2'', ''v3''], [''k1'', ''v1''], [''k1'', ''v2'']]

Or would you prefer an inscrutable one-liner ;-)

Note that there is no guarantee of any particular order in d.items(),
though you could sort them:
d = {''k1'':[''v1'',''v2''],''k2'':''v3''}
flat = []
items = d.items()
items.sort() # on keys
for k,v in items: ... if isinstance(v,list):
# Note that v is a list here, but does have pre-existing order you might want to keep.
# If you wanted to guarantee sorted output of the v2''s, you could
# do v.sort() here, though you might surprise others holding references
# to those lists, since they would see the sorting. To avoid that, make a copy first, e.g.,
# v = v[:]; v.sort() #(untested, but I think it should work ;-)

... for v2 in v:
... flat.append([k,v2])
... else:
... flat.append([k,v])
... flat



[[''k1'',''v1''],[''k1'',''v2 ''],[''k2'','''v3'']


问候,

Bengt Richter


[[''k1'', ''v1''], [''k1'', ''v2''], [''k2'', ''v3'']]

Regards,
Bengt Richter


肯定会有人提出比这个更好的解决方案,但

这对你来说至少可以作为第一次尝试


导入类型

def flatten(d,iterables =(types.ListType,types.TupleType)):

rv = []

for k,v in d.items():

如果在迭代中输入类型(v):

rv + = [[k,x] for x in v]

其他:

rv + = [[k,v]]

返回rv


如果你想要改变被迭代的东西的类型,只需要通过a。
传递你自己的第二个参数。


希望有所帮助,

Brandon


" Nicolas Girard" <镍******************* @ removethis.nerim.net>写在

消息新闻:pa *************************** @ removethis.neri m.net .. 。
Someone will definitely come up with a better solution than this, but
this could work for you at least as a first try

import types
def flatten(d, iterables=(types.ListType, types.TupleType)):
rv = []
for k, v in d.items():
if type(v) in iterables:
rv += [[k,x] for x in v]
else:
rv += [[k,v]]
return rv

If you want to change the types of things that get iterated over, just
pass in a second parameter of your own.

Hope that helps,
Brandon

"Nicolas Girard" <Ni*******************@removethis.nerim.net> wrote in
message news:pa***************************@removethis.neri m.net...


如果答案很简单,请原谅我,但是你能不能告诉我如何
达到以下目的:

{k1:[v1,v2],k2:v3,...} - > [[k1,v1],[k1,v2],[k2,v3],...]

微妙的一点(至少对我而言)是扁平化。
列出的值。
提前致谢,
Nicolas

---- ==通过Newsfeed.Com发布 - 无限制 - 未经审查 - 安全Usenet
新闻== ---- http://www.newsfeed.com # 1个世界新闻组服务!
100,000个新闻组
--- = 19个东/西海岸专业服务器 - 通过
Hi,

Forgive me if the answer is trivial, but could you tell me how to achieve the following:

{k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...]

The subtle point (at least to me) is to "flatten" values that are lists.
Thanks in advance,
Nicolas

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World!
100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via

进行全面隐私

加密= ---


Encryption =---


Nicolas Girard写道:
Nicolas Girard wrote:


如果答案很简单,请原谅我,但你能告诉我吗?如何实现
以下内容:

{k1:[v1,v2],k2:v3,...} - > [[k1,v1],[k1,v2],[k2,v3],...]

微妙的一点(至少对我而言)是扁平化。作为列表的值。


好​​吧,我至少可以在一定程度上解决你问题,但是你的原始数据结构存在歧义,导致问题:


1. d.items()会告诉你


[(k1,[v1,v2]),(k2,v3),...]


2.现在,你要扩展列表元素,其中每个元组的第二部分

是一个列表,你可以用它。 br />

flatten = lambda u:map(lambda x:(u [0],x),u [1])


或者,如果双lambda表达式令人困惑:


def flatten(u):

返回映射(lambda x:(u [0],x),u [ 1])


(我使用了元组(u [0],x)而不是列表,因为你的[k1,vn]

总是成对,但如果你愿意,你可以使用一个列表。


然后展平将采用嵌套元素


(k1,[ v1,v2])


并将其转换为元组列表


[(k1,v1),[k2,v2]) ]


3.你想申请fl关注d.items()的每个元素,你可以用b / b
来完成


lol = map(flatten,d.items())


将为您提供元组列表的列表,


4.然后将其减少为元组列表


减少(operator.add,lol)

不幸的是,这与上面的例子并不完全一致,因为

flatten won''应用于(k2,v3)时,工作正常。如果v3是一个

序列,它会给你[(k2,v3 [0]),(k2,v3 [1]),...],

这可能不是你想要的(特别是如果v3是一个字符串 - 尝试

手动压扁,看看会发生什么)。如果v3不是序列,你会得到一个TypeError,说map()的参数2必须支持迭代。


如果你*知道* v3永远不会成为一个列表,你可以修改flatten to

处理特殊情况如下:


def flatten(u):

if isinstance(u [1],type([])):

return(u [1],[u [2]])

返回映射(lambda x:(u [0],x),u [1])


或者,如果你可以修改初始字典的生成方式

以确保密钥具有单个值的情况始终显示为

k2:[v3]而不是k2:v3,那么您可以使用上述步骤而无需

修改。如果可行的话,这可能会更好,因为你的原始数据结构本质上是模棱两可的,除非你知道v3

永远不会是一个列表。


David


提前致谢,Nicolas

---- ==通过Newsfeed.Com发布 - 无限 - 未经审查的安全Usenet新闻== ----
http://www.newsfeed.com 世界排名第一的新闻组服务! > 100,000个新闻组
--- = 19个东/西海岸专业服务器 - 通过加密的总隐私= ---
Hi,

Forgive me if the answer is trivial, but could you tell me how to achieve
the following:

{k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...]

The subtle point (at least to me) is to "flatten" values that are lists.
Well, I can get you at least part way, but there is an ambiguity in your
original data structure which causes problems:

1. d.items() will get you

[(k1, [v1, v2]), (k2, v3), ...]

2. Now, you want to expand out the list elements where the second part
of each tuple is a list, which you can do with.

flatten = lambda u: map(lambda x: (u[0], x), u[1])

or, if the double lambda expression is confusing:

def flatten(u):
return map(lambda x: (u[0], x), u[1])

(I''ve used a tuple (u[0], x) instead of a list, because your [k1, vn]
are always pairs, but you can use a list if you prefer)

Then flatten will take the nested element

(k1, [v1, v2])

and convert it to a list of tuples

[(k1, v1), [k2, v2])]

3. You want to apply flatten to each element of d.items(), which you
can do with

lol = map(flatten, d.items())

which will give you a list of lists of tuples,

4. and then reduce that to a list of tuples with

reduce(operator.add, lol)
Unfortunately, this doesn''t quite work with your example above, because
flatten won''t work properly when applied to (k2, v3). If v3 is a
sequence, it will instead give you [(k2, v3[0]), (k2, v3[1]), ...],
which is probably not what you want (especially if v3 is a string - try
flatten manually and see what happens). If v3 is not a sequence, you''ll
get a TypeError saying that argument 2 to map() must support iteration.

If you *know* that v3 will NEVER be a list, you can modify flatten to
handle the special case like so:

def flatten(u):
if isinstance(u[1], type([])):
return (u[1], [u[2]])
return map(lambda x: (u[0], x), u[1])

Alternatively, if you can modify how the initial dictionary is generated
to ensure that cases where a key has a single value always appear as
k2: [v3] instead of k2: v3, then you can use the steps above without
modification. This is probably better if it is feasible, because your
original data structure is inherently ambiguous unless you know that v3
will never be a list.

David


Thanks in advance,
Nicolas

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---






这篇关于Dict to“flat” (键,值)列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆