Python str.format()字典列表

时间:2016-09-27 20:46:58

标签: python list dictionary format

我正在尝试开发一种在迭代字典列表时以某种方式打印的格式。

引发错误:"元组索引超出范围"

我已经查看了其他一些类似主题的问题,并且知道您无法使用数值和格式()。至少那是我从中获得的。

在我的情况下,我没有使用数值,所以不确定为什么它不起作用。我想我知道如何使用其他(%S)格式化方法解决这个问题,但试图压缩并使我的代码更加pythonic。

因此,当我删除.formate语句并保留索引参数时,我得到了正确的值,但是一旦我尝试格式化它们,我就会收到错误。

我的代码:

def namelist(names):
    n = len(names)
    return_format = {
    0: '{}',
    1: '{} & {}',
    2:'{}, {} & {}'
    }
    name_stucture = return_format[n-1]
    for idx, element in enumerate(names):
        print name_stucture.format(names[idx]["name"])

正在寻找为什么会这样,以及如何解决它,谢谢!

2 个答案:

答案 0 :(得分:1)

这个问题似乎比你想要的更简单:

// Quote model
type Quote struct {
    Id        bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
    Author     string        `json:"author" form:"author" binding:"required" bson:"author"`
    Body      string        `json:"body" form:"body" binding:"required" bson:"body"`
    Tag       []string      `json:"tag" bson:"tag"`

}

<强>输出

formats = [None, '{}', '{} & {}']

def namelist(names):
    length = len(names)

    if length > 2:
        name_format = '{}, ' * (length - 2) + formats[2]  # handle any number of names
    else:
        name_format = formats[length]

    print(name_format.format(*names))

namelist(['Tom'])
namelist(['Tom', 'Dick'])
namelist(['Tom', 'Dick', 'Harry'])
namelist(['Groucho', 'Chico', 'Harpo', 'Zeppo'])

# the data structure is messy so clean it up rather than dirty the function:
namelist([d['name'] for d in [{'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]])

答案 1 :(得分:0)

当您尝试使用参数太少来解压缩格式字符串时,会出现错误。这是一个基本的例子:

>>> '{}{}'.format('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

即使您将列表作为一个参数传递,也会发生这种情况。您需要使用星号解压缩列表:

没有拆包:

>>> x = ['one', 'two']
>>> '{}{}'.format(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

解压缩:

>>> x = ['one', 'two']
>>> '{}{}'.format(*x)
'onetwo'

修改

还有一些其他问题:您循环遍历每个名​​称并打印指定的格式,但除非您希望每次打印三次名称,否则根本不需要循环。使用names[idx]而不仅仅是element也是不必要的,也是不需要的。

保留一些模式,这是一个有效的例子:

names = [ {'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]

def namelist(names):
  name_structure = ['{}', '{} & {}', '{}, {}, & {}'][min(2, len(names) - 1)]
  name_structure.format(*[name['name'] for name in names])

请注意,如果您有三个以上的名称,此函数将出现意外行为:它只会打印前三个名称。