简体   繁体   English

连接不同长度的字典元组中的字符串

[英]Concatenating strings from dictionary tuples with different lengths

I have a dictionary created with basketball player positions, with the key being the players name and the value being a tuple with their position(s).我有一个用篮球运动员位置创建的字典,键是球员姓名,值是他们位置的元组。 For example: {'Player1': ('SF', 'PF'), 'Player2': 'C', 'Player3': 'SG'}例如:{'Player1': ('SF', 'PF'), 'Player2': 'C', 'Player3': 'SG'}

I'm trying to concatenate each players position(s) with another string, but when I try to select the second value it ends up slicing the first value instead.我试图将每个玩家的位置与另一个字符串连接起来,但是当我尝试 select 第二个值时,它最终会切片第一个值。

Is there a way to loop through the keys and each individual value for every player or do I need to make a nested loop for the conditions where the tuple has multiple values?有没有办法循环遍历每个玩家的键和每个单独的值,或者我是否需要为元组具有多个值的条件创建一个嵌套循环?

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

creates an error because obviously certain positions won't have that index, so I'm wondering if there is there another loop I can use to test whether the value has multiple items?创建一个错误,因为显然某些位置不会有该索引,所以我想知道是否还有另一个循环可以用来测试该值是否有多个项目? I've tried using len() but that either returns the string length if its a single position or the tuple length so that doesn't differentiate enough.我尝试过使用 len() ,但是如果它是单个 position 或元组长度,则返回字符串长度,这样就不足以区分。

You could maybe use isinstance() before checking with len() :您可以在检查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}')

Output: Output:

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

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

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