我创建了一个篮球运动员位置字典,键是球员的名字,值是一个包含他们位置的元组。例如:{"第1层":("SF","PF"(,"Player2":"C","Player3":"SG"}
我试图用另一个字符串连接每个玩家的位置,但当我尝试选择第二个值时,它最终会将第一个值切片。
有没有一种方法可以循环遍历每个玩家的键和每个单独的值,或者我需要为元组有多个值的条件做一个嵌套循环?
for k,v in player_position_dict.items():
print(v[1])
创建了一个错误,因为显然某些位置没有该索引,所以我想知道是否还有另一个循环可以用来测试该值是否有多个项?我尝试过使用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}')
输出:
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