好的。我有一个 CSV,我正在尝试使用格式功能重新排列列数据的打印顺序。
换句话说,我如何使用格式函数以 e、d、c 的顺序打印列,而不是默认的 c、d、e?
这是我目前所拥有的:
for row in books:
print [item.upper() for item in row]
print [format(item[])
我在这里错过了什么?
最佳答案
格式化字符串
我不确定你要什么,但这可能符合你的需要:
>>> my_items = ['c', 'd', 'e']
>>> print '{2} {1} {0}'.format(*my_items)
e d c
它使用格式,允许您按您喜欢的任何顺序 打印项目。参见 documentation of format()
了解更多。
反转列表
如果您只想反转数组的顺序,只需在列表名称后的括号内为“step”部分提供-1
:
>>> my_items = ['c', 'd', 'e']
>>> my_items[::-1]
['e', 'd', 'c']
因此您的代码可能如下所示:
for row in books:
print [item.upper() for item in row[::-1]]
这将连续打印大写项目列表,但顺序相反。
关于python - 使用格式化函数没有得到我想要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8272027/