【问题标题】:Concatenating strings from dictionary tuples with different lengths连接不同长度的字典元组中的字符串
【发布时间】:2022-01-09 13:54:39
【问题描述】:

我有一个用篮球运动员位置创建的字典,键是球员的名字,值是一个包含他们位置的元组。例如: {'Player1': ('SF', 'PF'), '玩家2':'C', 'Player3': 'SG'}

我正在尝试将每个玩家的位置与另一个字符串连接起来,但是当我尝试选择第二个值时,它最终会切割第一个值。

有没有办法循环遍历每个玩家的键和每个单独的值,或者我是否需要针对元组具有多个值的条件进行嵌套循环?

for k,v in player_position_dict.items():
    print(v[1])

创建一个错误,因为显然某些位置不会有该索引,所以我想知道是否还有另一个循环可以用来测试该值是否有多个项目?我尝试过使用 len() 但如果它是单个位置或元组长度则返回字符串长度,因此区分不够。

【问题讨论】:

  • 你有预期的输出吗?
  • 你写“......并且值是一个带有它们位置的元组”,但是你显示一个字典,其中一些值是元组,其他值是字符串。是哪个?

标签: python dictionary tuples


【解决方案1】:

您可以在检查 len() 之前使用 isinstance()

player_position_dict = {
    'Player1': ('SF', 'PF'),
    'Player2': 'C',
    'Player3': 'SG',
    'Player4': ('PG'),
}
some_string_to_concentate_with = 'some_string_to_concentate_with'
for player, position in player_position_dict.items():
    if isinstance(position, tuple):
        if len(position) > 1:
            print(f'{player} has multiple positions:')
            for pos in position:
                print(f'{some_string_to_concentate_with}_{pos}')
        elif len(position) == 1:
            print(f'{player} has one position:')
            print(f'{some_string_to_concentate_with}_{position[0]}')
    else:
        print(f'{player} has one position:')
        print(f'{some_string_to_concentate_with}_{position}')

输出:

Player1 has multiple positions:
some_string_to_concentate_with_SF
some_string_to_concentate_with_PF
Player2 has one position:
some_string_to_concentate_with_C
Player3 has one position:
some_string_to_concentate_with_SG
Player4 has one position:
some_string_to_concentate_with_PG

【讨论】:

  • 只是好奇 - 您是否有理由使用 bold text 而不是 code format 来表示 isinstance()len()?
  • 人们(即 OP)更有可能在内容为粗体时实际点击链接。我通常使用 [str.<b>upper()</b>](http...) 之类的东西,其中在适当的时候也只有部分文本是粗体的。但是这次我只是忘记添加代码格式了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 2016-08-21
  • 2012-12-23
  • 2018-06-21
相关资源
最近更新 更多