python - 连接来自不同长度的字典元组的字符串

标签 python dictionary tuples

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

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

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

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

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

最佳答案

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

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

关于python - 连接来自不同长度的字典元组的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70210210/

相关文章:

python - 使用 Counter 创建字典

python - 整数元组的条件

python - 如何按字母顺序按第一个元素(字符串)对元组列表进行排序[PYTHON]

python - 在 Python 中获取 Windows 上的系统环境变量

c# - 如何在 C# 中比较字典列表的相等性

python - 从列表列表创建字典

c# - 如何在值元组中使用泛型类型?

Python 3 : Returning a new child class instance from an inherited method, 当子构造函数的参数多于父构造函数时

Python tkinter : Add button to menu bar

python - 算法,列表元素之间的最近点