首页 > 解决方案 > 对列表使用字符串格式

问题描述

我有一个列表列表,我需要使用字符串格式打印它。如果列表中有一个“x”,我需要它显示一个“*”。

我还需要计算计数和未计数的项目,我所得到的不能正常工作。请参阅输出以进行说明。

list = [
['animal', 'cat', 2017, 'x'],
['cutlery', 'fork', 2007, 'o'],
['furniture', 'chair', 2019, 'x']
]

要将索引号添加到项目中,我使用了枚举,效果很好。为了格式化,我使用了字符串格式化,效果很好。我坚持的部分是我需要将 'x' 转换为 '*' 和 'o' 转换为 ' ' 以及如何显示计数和未计数的项目。

我到目前为止的代码:

for index, item in enumerate(list):
    print('{}. {} {} - {} ({})'.format(index, item[3], item[0], item[1], item[2]))
counted_items = list[4].count("x")
uncounted_items = list[4].count("o")
print("{} items counted, {} items still to count".format(counted_items, uncounted_items))
Current output with error:
0. x cat - 2017 (animal)
1. 0 fork - 2007 (cutlery)
2. x chair - 2019 (furniture)
Traceback (most recent call last):
counted_items = list[3].count("x")
IndexError: list index out of range
What output should look like:
0. * cat - 2017 (animal)
1.   fork - 2007 (cutlery)
2. * chair - 2019 (furniture)
2 items counted, 1 item too count

其中 '*' 等于计数

标签: python-3.x

解决方案


这可能是您需要的。

list = [
['animal', 'cat', 2017, 'x'],
['cutlery', 'fork', 2007, 'o'],
['furniture', 'chair', 2019, 'x'],
]
c1 = c2 = 0
for index, item in enumerate(list):
  if item[3] == 'x':
    item[3] = '*'
    c1 += 1
  if item[3] == 'o':
    item[3] = ' '   
    c2 += 1
  print('{}. {} {} - {} ({})'.format(index, item[3], item[0], item[1], item[2]))

print(c1,' item(s) counted, and ',c2,' item(s) uncounted!')

我已经测试过了。希望能帮助到你 !


推荐阅读