作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
例如,假设我有两个文本文件 test_keys.txt
2
5
7
和test_values.txt
ace
ventura
pet detective
我将这些文件制作成字典的代码如下。
with open('test_keys.txt') as file1:
keys = file1.readlines()
with open('test_values.txt') as file2:
values = file2.readlines()
print(sorted(dict(zip(keys,values)).items()))
我得到的内容
[(' 2\n', 'ace\n'), (' 5\n', 'ventura\n'), ('7', 'pet detective')]
如何去掉结果中的\n 和数字之前的空格?我在 file1.readlines() 之后尝试了 .replace('\n', '') ,并得到一个“list”对象没有属性“replace”的错误。有什么建议吗?
最佳答案
使用列表理解将键转换为数字并删除值:
keys = [int(key) for key in keys]
values = [value.strip() for value in values]
然后按照您的代码进行操作。
关于python - 如何将两个文本文件放入字典(小修复)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984966/
我是一名优秀的程序员,十分优秀!