gpt4 book ai didi

python 3.5 : Is there a way to make this list more organized?

转载 作者:行者123 更新时间:2023-11-28 20:12:41 25 4
gpt4 key购买 nike

假设您有以下代码:

bicycles = ['Trek','Cannondale','Redline','Secialized']
print(bicycles[0],bicycles[1],bicycles[2],bicycles[3])

这将打印出:

Trek Cannondale Redline Specialized

我有两个问题。 首先,有没有一种方法可以使打印字符串更有条理,这样您就不必多次输入自行车?我知道如果您只是这样做:

print(bicycles)

它还会打印括号,这是我试图避免的。

第二个问题,打印时如何插入逗号以在列表中显示?

这就是我想要的结果:

Trek, Cannondale, Redline, Specialized.

我知道我可以做到

print("Trek, Cannondale, Redline, Specialized.")

但是使用列表是否可以使它更有条理?或者将句子打印出来是最明智的做法吗?

最佳答案

use .join() method:

The method join() returns a string in which the string elements of sequence have been joined by str separator.

syntax: str.join(sequence)

bicycles = ['Trek','Cannondale','Redline','Secialized']
print (' '.join(bicycles))

输出:

Trek Cannondale Redline Secialized

示例:将分隔符更改为 ', ':

print (', '.join(bicycles))

输出:

Trek, Cannondale, Redline, Secialized

For python 3. you can also use unpacking:

We can use * to unpack the list so that all elements of it can be passed as different parameters.

We use operator *

bicycles = ['Trek','Cannondale','Redline','Secialized']
print (*bicycles)

输出:

Trek Cannondale Redline Secialized

注意:它使用 ' ' 作为默认分隔符,或者指定一个分隔符,例如:

print(*bicycles, sep=', ')

输出:

Trek, Cannondale, Redline, Secialized

如果列表中的元素是不同类型(无需显式转换为字符串),它也可以工作

例如,如果自行车是 ['test', 1, 'two', 3.5, 'something else']

bicycles = ['test', 1, 'two', 3.5, 'something else']
print(*bicycles, sep=', ')

输出:

test, 1, two, 3.5, something else

关于 python 3.5 : Is there a way to make this list more organized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com