繁体   English   中英

从字典创建特定类型的元组(python)

[英]Creating an specific kind of tuple from a dictionary (python)

首先,我对编程很陌生。 (这是我在溢出中的第二个问题。)

我已经学习了近6个小时。 我在stackoverflow和许多其他python网站上读了很多。 我的大部分疑惑都消失了,现在我有了一个我无法真正解决的疑虑。

看,我有这个简单的字典:

player_dict = {'Alice': Rating(),
           'Bob': Rating(),
           'Carla': Rating(),
           'Daniel': Rating(),
           'Esdras': Rating(),
           'Flavia': Rating(),
           'Glauber': Rating(),
           'Hudson': Rating(),
           'Iara': Rating(),
           'Josiane':Rating()}

rating()方法创建一个像这样的元组

trueskill.Rating(mu=25, sigma=8.33333)

要更新那些评级,我应该在类似这样的情况下使用Rating()对象

rating_groups = [(player_dict['Alice'],), (player_dict['Bob'],), (player_dict['Carla'],),
                (player_dict['Daniel'],), [...brevity] ]

当我打印(rating_groups)时,IDLE向我返回此信息:

[(trueskill.Rating(mu=25, sigma=8.33333),), (trueskill.Rating(mu=25, sigma=8.33333),), [...brevity]

所以,这是我的问题。 最后一个元组在右括号旁边有这个“奇怪的”第二个逗号。 我已经知道对我正在执行的代码(API的Cuz)是必要的。 我想知道的是如何在这样的元组中转换player_dictionary。 我不太确定,但是看起来我正在使用元组的元组。

我已经在这里尝试过此代码: player_listTuple = [(v, k) for v, k in player_dict.items()]而Idle返回给我这个

[('Alice', trueskill.Rating(mu=25.0, sigma=8.33333)), ('Bob', trueskill.Rating(mu=25.0, sigma=8.33333)),

没有我期望看到的逗号。

感谢您的支持<3

要将player_dictionary转换为元组列表,可以尝试以下操作:

[(item,) for item in player_dictionary.values()]

comma用于区分tuple()包围的expression

例如:

>>> s = ('hello_world')
>>> type(s)
<type 'str'>
>>> 
>>> s = ('hello_world',)
>>> type(s)
<type 'tuple'>

对于1 item ,不需要添加即可添加多余的comma 见前:

>>> s = (1, 2)
>>> type(s)
<type 'tuple'>
>>> print(s)
(1, 2)
>>> 
>>> s1 = (1, 2,)
>>> print(s1)
(1, 2)
>>> print(s1)
(1, 2)

假设您需要添加comma ,可以执行以下操作,

player_listTuple = [(v, k, None) for v, k in player_dict.items()]

暂无
暂无

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

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