这是在Python中编写长列表的最简洁方法吗?

hky*_*404 5 python pep8

def kitchen():
    kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
    ]
Run Code Online (Sandbox Code Playgroud)

我试过读PEP8,但我从那里得到的唯一的东西是 -

多行结构上的右括号/括号/括号可以在列表最后一行的第一个非空白字符下排成一行

我真的不明白这意味着什么.我很抱歉没有正确阅读.

the*_*eye 11

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

kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
]
Run Code Online (Sandbox Code Playgroud)

要么

kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
    ]
Run Code Online (Sandbox Code Playgroud)


Tha*_*tos 5

您引用的部分:

多行结构上的右大括号/方括号/圆括号可以排列在列表最后一行的第一个非空白字符下

老实说,这正是它所说的意思:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',  <-- "the last line of the list"
    ^
    "the first non-whitespace character"
Run Code Online (Sandbox Code Playgroud)

因此:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',
    ]
Run Code Online (Sandbox Code Playgroud)

还有PEP-8提到的第二个选项,

或者它可以排列在开始多行结构的行的第一个字符下,如下所示:

"the first character"
v
my_list = [  <-- "line that starts the multi-line construct"
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',
Run Code Online (Sandbox Code Playgroud)

因此:

my_list = [
    'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h',
]
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我更喜欢第二种风格,因为它提供了一种很好的方式来扫描列表的末尾:]justs 回到左侧:

my_list = [
|    'items', 'items',
|    'items', 'items',
|  < a nice line for your eye to track
|
|
]  < this stands out more
Run Code Online (Sandbox Code Playgroud)