gpt4 book ai didi

python - 使用 % 进行 For 循环解析

转载 作者:行者123 更新时间:2023-12-01 08:41:54 24 4
gpt4 key购买 nike

一个月前刚开始学习Python。我被一个问题难住了。尝试使用 for 循环更新字典。我想使用 for 循环的变量名作为键,使用变量值作为字典的值来存储变量。我正在尝试使用 % 使其成为单行。这是我到目前为止所拥有的:

grbl_parser_d = {
'a': 'null', # Motion Mode
'b': 'null', # Coordinate System Select
'c': 'null' # Plane Select
}

grbl_out = [GC:G0 G54 G17]

def filtergrblparser():
global grbl_parser_d
for l, r in [grbl_out.strip('[]').split(':')]:
for a, b, c in [r.split(' ')]:
# grbl_parser_d.update({'%': x}) % x
grbl_parser_d.update({'a': a})
grbl_parser_d.update({'b': b})
grbl_parser_d.update({'c': c})

“grbl_out”变量是 Arduino 的输出。

尝试使用类似:grbl_parser_d.update({'%': a}) % a.name

'a.name' 将是 for 循环的变量名称,而不是值。这可能吗?任何其他清理代码的建议和技巧也将不胜感激。谢谢!

最佳答案

您不需要为此循环,而且我不会尝试将其塞到一行中。这是一个简单的函数,应该可以完成您想要的操作。

def filtergrblparser(grbl_out):
l, r = grbl_out.strip('[]').split(':')
a, b, c = r.split(' ')
grbl_parser_d = {
'a': a, # Motion Mode
'b': b, # Coordinate System Select
'c': c # Plane Select
}
return grbl_parser_d

# I'm assuming you meant this to be a string
grbl_out = "[GC:G0 G54 G17]"

grbl_parser_d = filtergrblparser(grbl_out)

print(grbl_parser_d)
# {'a': 'G0', 'b': 'G54', 'c': 'G17'}

关于python - 使用 % 进行 For 循环解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com