使用变量字符串命名另一个变量(Python)[重复](Use a variable string to name another variable (Python) [duplicate])

系统教程 行业动态 更新时间:2024-06-14 17:02:18
使用变量字符串命名另一个变量(Python)[重复](Use a variable string to name another variable (Python) [duplicate])

这个问题在这里已有答案:

如何从字符串列表中创建列表? 2个答案

我有一个列表,我想在对象的命名中使用信息。 例如:

print this_device # ex. output ['dev879:', 'drain', '7.474', '11.163', '18.637']

我想做的是使用this_device[0]作为用于创建对象的下一个变量的名称。

例如:

print this_device # ex. ['dev879:', 'drain', '7.474', '11.163', '18.637'] Drive_DeviceName_ = this_device[0] # which is 'dev879' Drivedev879 = ReadableDevice(this_device[0], this_device[1], this_device[2])

如果这有意义,请告诉我。

This question already has an answer here:

How can I create lists from a list of strings? 2 answers

I have a list that I would like to use information from in the naming of an Object. for example:

print this_device # ex. output ['dev879:', 'drain', '7.474', '11.163', '18.637']

What I would like to do it use this_device[0] to be the name of the next variable to use to create an object.

For example:

print this_device # ex. ['dev879:', 'drain', '7.474', '11.163', '18.637'] Drive_DeviceName_ = this_device[0] # which is 'dev879' Drivedev879 = ReadableDevice(this_device[0], this_device[1], this_device[2])

Please let me know if this makes sense.

最满意答案

据我所知,这是不可能的。 你可以做的是从列表中创建一个字典,并使用你想要的名称作为键。

devices = {} devices['name'] = this_device[0] etc...

通过从原始列表中创建属性名称列表,可以更快地完成此操作。 我假设您提供的列表是属性列表。

props = ['name', 'prop_1', 'prop_2', ...] this_device = ['dev879:', 'drain', '7.474', '11.163', '18.637'] device = dict(zip(props, this_device))

将导致:

{'name': 'dev870', 'prop_1': 'drain', ..}

As far as I know that isn't possible. What you can do is to create a dictionary from the list and use the names you would like as keys.

devices = {} devices['name'] = this_device[0] etc...

This could be done faster by creating a list of the property names from your original list. I'm assuming that the list you provided is a list of properties.

props = ['name', 'prop_1', 'prop_2', ...] this_device = ['dev879:', 'drain', '7.474', '11.163', '18.637'] device = dict(zip(props, this_device))

will result in:

{'name': 'dev870', 'prop_1': 'drain', ..}

更多推荐

本文发布于:2023-04-21 18:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/0079211a440f1ad7c4ed465d3bd8008f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   字符串   Python   duplicate   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!