提问人:Hazel P 提问时间:7/24/2023 最后编辑:mkrieger1Hazel P 更新时间:7/25/2023 访问量:77
如何在数字列表中添加分隔符?[复制]
How can I add separators to lists of numbers? [duplicate]
问:
我正在做一个练习,它告诉我打印出每个人最喜欢的数字。当涉及到有多个数字的人时,我无法将数字保持在一行中,用逗号分隔。你能提出一个解决方案吗?
我的代码
favourite_numbers = {
"ha": [20, 10, 4],
"quynh": [2, 5],
"nhung": [3, 10, 12],
"giang": [10],
}
for name, numbers in favourite_numbers.items():
if len(numbers) == 1:
for number in numbers:
print(f"\n{name.title()}'s favourite number is {number}.")
elif len(numbers) >= 2:
print(f"\n{name.title()}'s favourite numbers are:")
for number in numbers:
print(f"{number}")
具有多个数字的人的输出如下所示
Ha's favourite numbers are:
20
10
4
我原以为会是这样的:
Ha's favourite numbers are: 20, 10, 4
答:
1赞
richard
7/24/2023
#1
Python String join() 方法似乎会有所帮助。
favourite_numbers = {
"ha": [20, 10, 4],
"quynh": [2, 5],
"nhung": [3, 10, 12],
"giang": [10],
}
for name, numbers in favourite_numbers.items():
if len(numbers) == 1: length = 'number is'
elif len(numbers) > 1: length = 'numbers are'
numbers = ', '.join(map(str, numbers))
print(f"\n{name.title()}'s favourite {length}", numbers)
输出:
Ha's favourite numbers are 20, 10, 4
Quynh's favourite numbers are 2, 5
Nhung's favourite numbers are 3, 10, 12
Giang's favourite number is 10
-1赞
DevManX
7/24/2023
#2
favourite_numbers = {
"ha": [20, 10, 4],
"quynh": [2, 5],
"nhung": [3, 10, 12],
"giang": [10]
}
for name in favourite_numbers:
numbers_in_line = ""
i = 1
count = len(favourite_numbers[name])
for number in favourite_numbers[name]:
if i == count:
comma = ""
numbers_in_line += str(number) + comma
else:
comma = ", "
numbers_in_line += str(number) + comma
i += 1
print(f"{name}'s favourite numbers are: {numbers_in_line}")
输出将如下所示:
ha's favourite numbers are: 20, 10, 4
quynh's favourite numbers are: 2, 5
nhung's favourite numbers are: 3, 10, 12
giang's favourite numbers are: 10
下面是在 PyCharm 上执行代码后的打印屏幕:
评论
0赞
Codist
7/24/2023
您的代码不会生成该输出
0赞
DevManX
7/24/2023
确实如此,我又检查了两次,您只需要确保缩进正确,并且打印发生在第一个循环的末尾。我将添加一个打印屏幕,以显示结果。
0赞
Hazel P
7/24/2023
我很欣赏你的回答。实际上,你得到的输出并不是我想要的。有一个人只有 1 个最喜欢的号码,所以输出应该是“Giang 最喜欢的号码是”而不是“[...]数字是”。
0赞
Codist
7/24/2023
@YasserKhalil 您的原始答案未产生所需的输出。您当前的版本确实可以工作,尽管效率非常低
0赞
Codist
7/24/2023
#3
当值列表中有多个数字时,可以通过对 print() 进行两次调用来执行此操作。在对 print() 的第二次调用中,只需解压缩列表:
favourite_numbers = {
"ha": [20, 10, 4],
"quynh": [2, 5],
"nhung": [3, 10, 12],
"giang": [10],
}
for k, v in favourite_numbers.items():
s = 's are' if len(v) > 1 else ' is'
print(f"{k.title()}'s favourite number{s} ", end='')
print(*v, sep=', ')
(可选)使用 map/join,如下所示:
for k, v in favourite_numbers.items():
s = 's are' if len(v) > 1 else ' is'
print(f"{k.title()}'s favourite number{s}", ', '.join(map(str, v)))
输出:
Ha's favourite numbers are 20, 10, 4
Quynh's favourite numbers are 2, 5
Nhung's favourite numbers are 3, 10, 12
Giang's favourite number is 10
评论
0赞
Hazel P
7/24/2023
谢谢你@DarkKnight。您能解释一下最后一个 print() 中的 *v 是如何工作的吗?
0赞
Codist
7/24/2023
我向你推荐 PEP 3132:peps.python.org/pep-3132
上一个:拆分名称序列数组中的列
评论