python-3.x - 对列表使用字符串格式
问题描述
我有一个列表列表,我需要使用字符串格式打印它。如果列表中有一个“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
其中 '*' 等于计数
解决方案
这可能是您需要的。
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!')
我已经测试过了。希望能帮助到你 !
推荐阅读
- shell - 使用 shell cmd 重命名 jenkins 中的目录
- javascript - 如何从脚本在 firefox/chrome 中运行 javascript 片段
- javascript - 使用相同的 jQuery 脚本重定向和修改新页面
- angular - Angular / Firebase - 类型“UserCredential”上不存在属性“电子邮件”
- vue.js - Vue-cli 3 - Webpack 4:无法使用 image-webpack-loader 加载 .webp 格式的图像
- python - 在谷歌应用引擎柔性环境中使用 stream_with_context 在烧瓶中加载栏
- php - 仅当我的数据变量不为空时如何专注于表单字段
- r - R: `rm(list=ls())` 有什么作用?
- mysql - MySQL查询以查找两次之间的可用插槽
- python - 在 Python 中加载 C 库会打开另一个 C 库 - 未解析的共享符号