简体   繁体   English

从元组列表中创建对词典的优雅方式?

[英]Elegant way to create a dictionary of pairs, from a list of tuples?

I have defined a tuple thus: (slot, gameid, bitrate) 我已经定义了一个元组:( slot,gameid,bitrate)

and created a list of them called myListOfTuples . 并创建了一个名为myListOfTuples的列表。 In this list might be tuples containing the same gameid . 在此列表中可能是包含相同gameid元组。

Eg the list can look like: 例如,列表可能如下所示:

[
   (1, "Solitaire", 1000 ),
   (2, "Diner Dash", 22322 ),
   (3, "Solitaire", 0 ),
   (4, "Super Mario Kart", 854564 ),
   ... and so on.
]

From this list, I need to create a dictionary of pairs - ( gameId , bitrate ), where the bitrate for that gameId is the first one that I came across for that particular gameId in myListOfTuples . 从这个列表中,我需要创建一个对的字典 - ( gameIdbitrate ),其中gameIdbitrate是我在gameIdmyListOfTuples的第一个特定myListOfTuples

Eg From the above example - the dictionary of pairs would contain only one pair with gameId "Solitaire" : ("Solitaire", 1000 ) because 1000 is the first bitrate found. 例如,从上面的例子中 - 对的字典只包含gameId “Solitaire”:( ("Solitaire", 1000 )因为1000是第一个找到的比特率。

NB. NB。 I can create a set of unique games with this: 我可以创建一组独特的游戏:

uniqueGames = set( (e[1] for e in myListOfTuples ) )

For python2.6 对于python2.6

dict(x[1:] for x in reversed(myListOfTuples))

If you have Python2.7 or 3.1, you can use katrielalex's answer 如果你有Python2.7或3.1,你可以使用katrielalex的答案

{ gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( )

(This is a view, not a set. It has setlike operations, but if you need a set, cast it to one.) (这是一个视图,而不是一个集合。它具有setlike操作,但如果你需要一个集合,则将其转换为一个。)

Are you sure you want a set, not a dictionary of gameId: bitrate ? 你确定你想要一套,而不是gameId: bitrate字典gameId: bitrate The latter seems to me to be a more natural data structure for this problem. 在我看来,后者对于这个问题来说是更自然的数据结构。

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

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