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

时间:2014-04-10 05:00:47

标签: python pep8

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

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

  

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

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

2 个答案:

答案 0 :(得分:9)

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

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"
    ]

答案 1 :(得分:3)

您引用的部分:

  

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

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

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