python-3.x - 使用 for loop .splitlines 循环将键和值添加到字典
问题描述
我试图读取一个字符串并将第一行作为键添加到字典中,将第二行作为值添加到文件末尾。所以 1 到键,2 到值,1 到键,2 到值,1 到键,2 到值......直到文件结束。
我试图从字符串中添加键和值。当我编写 8 个循环时,它工作正常,但我只想使用一个循环。这是有效的 8 循环示例。
tmp_dic = {}
String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"
for x in String.splitlines()[0:1:]:
print(x)
x2 = x
tmp_dic[f"{x}"] = f""
for y in String.splitlines()[1:2:]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
for x in String.splitlines()[2:3:]:
print(x)
x2 = x
tmp_dic[f"{x}"] = f""
for y in String.splitlines()[3:4:]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
for x in String.splitlines()[4:5:]:
print(x)
x2 = x
tmp_dic[f"{x}"] = f""
for y in String.splitlines()[5:6:]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
for x in String.splitlines()[6:7:]:
print(x)
x2 = x
tmp_dic[f"{x}"] = f""
for y in String.splitlines()[7:8:]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
print(tmp_dic)
打印输出正确:
First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eight
字典也很好。
{'First': 'Second', 'Third': 'Fourth', 'Fifth': 'Sixth', 'Seventh': 'Eight'}
这是一个循环示例
tmp_dic = {}
String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"
c1 = 0
c2 = 1
for x in String.splitlines()[f"{c1}":f"{c2}":]:
tmp_dic[f"{x}"] = f""
c1 = c1 + 1
c2 = c2 + 1
for y in String.splitlines()[f"{c1}":f"{c2}":]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
c1 = c1 + 1
c2 = c2 + 1
print(tmp_dic)
我收到以下错误。但是 c1 和 c2 都是整数。
File "testdic3.py", line 12, in <module>
for x in String.splitlines()[f"{c1}":f"{c2}":]:
TypeError: slice indices must be integers or None or have an __index__ method
我也试过:
tmp_dic = {}
String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"
lengh = len(String.splitlines())
c1 = 0
c2 = 1
for I in range(lengh):
x = String.splitlines()[f"{c1}":f"{c2}":]:
tmp_dic[f"{x}"] = f""
c1 = c1 + 1
c2 = c2 + 1
for y in String.splitlines()[f"{c1}":f"{c2}":]:
print(y)
tmp_dic[f"{x2}"] = f"{y}"
c1 = c1 + 1
c2 = c2 + 1
print(tmp_dic)
解决方案
您的代码措辞奇怪。您可能想在问题中添加一个解释高级动机的句子。
假设我们分配lines = String.splitlines()
那么你想要的只是简单lines[c1:c2]
,而不是lines[f"{c1}":f"{c2}":]
。
(可以使用lines[c1:c2:]
,但 stepsize 默认为,1
因此不需要。您可以在反转时指定它,例如lines[c2:c1:-1]
。)
但是 c1 和 c2 都是整数。
真是的。但是一旦你将它们变成了字符串(使用 f 字符串格式化程序),那么你就不能再使用它们进行切片(或下标)了。
此外,pep-8要求您命名变量string
而不是String
. 我们将初始资本用于 aclass
而不是这样的 temp var。
编辑
当你用谷歌搜索某样东西时,你只是假设它已经存在,然后描述你想要的东西的样子。像魔术一样工作!
在编写程序时,您可以做出类似的假设。你说你想要(键,值)对。好吧,很公平,让我们假设 已经有一个功能可以提供它们:
def populate_dictionary():
d = {}
for k, v in get_pairs():
d[k] = v
return d
嗯,这很容易!但是等等,现在我们必须回到困难的部分,我们需要一个get_pairs()
定义。好消息是,现在我们正在解决一个较小的子问题,它更容易:
def get_pairs(input='First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight'):
lines = input.splitlines()
for i in range(len(lines) // 2):
yield lines[2 * i], lines[2 * i + 1]
达达!现在我们完成了。c1
(当然,如果您希望避免花哨的2 * i
表达式,则可以使用 temp var 。)它会产生以下输出:
{'First': 'Second',
'Third': 'Fourth',
'Fifth': 'Sixth',
'Seventh': 'Eight'}
(可以用 替换for
循环d.update(get_pairs())
,或者更简单地通过赋值来替换循环d = dict(get_pairs())
,但看起来您正在寻找该for
语句的练习。)
推荐阅读
- elasticsearch - Grafana 导数未显示正确的输出值
- sql - SQL 日期转换 HHMMSS.CCCNNNNNN 到 yyyy-mm-dd hh:mi:ss.mmm
- azure - 如何翻译应用程序授权窗口 Azure AD
- javascript - NodeJS 返回 SQL 查询以传递给另一个文件
- javascript - 角度模式形式的数组长度
- php - 尝试在自定义论坛上发布新主题时出现空白页面
- bash - bsub 命令内的输出重定向
- ios - #if canImport(module) 仍然无法解决 Swift 4.1 中的条件导入语句?
- c# - 试图在 iqueryable any 中进行切换
- amazon-web-services - 通过自动创建新的从机来自动缩放 Jenkins 实例