在Python中写长列表的最简洁方式是什么?

12 投票
2 回答
15490 浏览
提问于 2025-04-18 02:08
def kitchen():
    kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
    ]

我试着去读PEP8,但我从中只明白了一点 -

在多行结构中,闭合的括号可以和最后一行的第一个非空白字符对齐。

我真的不太明白这是什么意思。抱歉我没有好好读它。

2 个回答

5

你引用的那部分内容是:

多行结构的闭合大括号/方括号/圆括号可以和列表最后一行的第一个非空白字符对齐。

老实说,这句话的意思就是字面上的意思:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',  <-- "the last line of the list"
    ^
    "the first non-whitespace character"

所以:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',
    ]

还有第二种选择,PEP-8提到的,

或者它可以和开始多行结构的那一行的第一个字符对齐,如下所示:

"the first character"
v
my_list = [  <-- "line that starts the multi-line construct"
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',

所以:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',
]

我个人更喜欢第二种风格,因为这样可以很方便地找到列表的结束位置:]会回到左边。

my_list = [
|    'items', 'items',
|    'items', 'items',
|  < a nice line for your eye to track
|
|
]  < this stands out more
18

你需要像这样缩进列表的内容

kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
]

或者

kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
    ]

撰写回答