简体   繁体   English

如何在Python中将字符串列表转换为整数?

[英]How do I convert a list of strings to integers in Python?

I'm using a combobox in Python tkinter to represent the user of the program with a few readable options. 我在Python tkinter中使用组合框来表示程序的用户,并带有一些可读选项。 These options need to be converted to integers later in the code. 这些选项需要稍后在代码中转换为整数。 How do I do this efficiently? 我如何有效地做到这一点?

An example for my Combobox: 我的组合框的一个示例:

example1 = Combobox(values=['Engine', 'Network', ...]

What I am using now to convert each String value in the Combobox is a bulky If...Else construction like so: 我现在用来转换组合框中的每个String值的是一个笨重的If ... Else构造,如下所示:

config = example1.get()

if config == 'Engine':
    config = 0
elif config == 'Network':
    config = 1
...

I feel like this is an efficient yet sloppy way of coding. 我觉得这是一种高效但草率的编码方式。

I've tried something to do with enum but I can't figure out how to do it. 我已经尝试过与enum事情,但是我不知道该怎么做。

Any suggestions? 有什么建议么?

EDIT: For this specific example I do in fact need the index of the combobox. 编辑:对于这个特定的例子,我确实需要组合框的索引。 But what if the Combobox contains Strings that are not based on the index, for example: 但是,如果组合框包含不基于索引的字符串,例如:

...
example2 = Combobox(values=['Global', 'Action', 'Audio', 'Info']

config = example2.get()

if config == 'Global' or config == 'Action':
    config = 0
elif config = 'Audio':
    config = 1:
elif config == 'Info':
    config = 2
...

You can use a dictionnary 您可以使用字典

d = {"Engine" : 0, "Network" : 1 }
config = "Engine"
config = d.get(config) # config is now equal to 0

You can use method index of list to replace if-elif block following way: 您可以通过以下方法使用list方法index来替换if-elif块:

options = ['Engine', 'Network']
config = 'Network'
config = options.index(config)
print(config) # 1

options should be same list, as that one you deliver to values of Combobox . options应该与您传递给Combobox values的列表相同。 index return lowest index of given element inside list - in my example 1 , because options[1] is 'Network' . index返回列表内给定元素的最低索引-在我的示例1 ,因为options[1]'Network'

You could use config_idx = values.index(config) to get numeric config values for any entry in the values list. 您可以使用config_idx = values.index(config)来获取values列表中任何条目的数字config值。 This is more pythonic and concise. 这更加pythonic和简洁。

Solution to Example-1 示例1的解决方案

values = ['Engine', 'Network', 'Car', 'Bus', 'Train', 'Horse']
test_config = [values[x] for x in [0,2,4]]

#config = 'Network'

for config in test_config:
    print('{}: {}'.format(config, values.index(config)))

Output 产量

Engine: 0
Car: 2
Train: 4

Solution to Example-2 示例2的解决方案

Here the solution would be to define a list of rule groups, which is a list of lists. 此处的解决方案是定义规则组列表,即列表列表。 Each list represents a group of config values that you want to assign the same config id. 每个列表代表您要分配相同配置ID的一组配置值。

# Define a list of rule groups: a list of lists. 
#     Each list represents a group of 
#     config values to be identified 
#     by the same integer.
rule_groups = [['Engine', 'Network'], ['Car'], ['Bus'], ['Train'], ['Horse']]

# Get config ids
for config in values:
    for rule_group in rule_groups:
        if config in rule_group:
            print('{}: {}'.format(config, rules_group.index(rule_group)))

Output 产量

Engine: 0
Network: 0
Car: 1
Bus: 2
Train: 3
Horse: 4

Supplementary Code 补充代码

You could also specify the rule_groups as follows and let the code restructure them properly to make it a list of lists. 您还可以如下指定rule_groups ,并让代码正确地重组它们,以使其成为列表列表。 So, you only put those config values into a list that are grouped together. 因此,您只需将这些配置值放入分组在一起的列表中。 For the rest, you could just copy-paste from the values list. 对于其余的内容,您只需从values列表中复制粘贴即可。 This will help managing your code if you have a lot of config values, which may or may not increase/decrease over time based on future requirements. 如果您有大量的配置值,这将有助于管理您的代码,这些配置值可能会根据将来的要求随时间增加或减少。

rule_groups = [['Engine', 'Network'], 'Car', 'Bus', 'Train', 'Horse']

for i, rule_group in enumerate(rule_groups):
    if not isinstance(rule_group,list):
        rule_groups[i] = [rule_group,]

rule_groups

Output 产量

[['Engine', 'Network'], ['Car'], ['Bus'], ['Train'], ['Horse']]

If you respect the order of your combo values you can use .current() method of the 如果您遵守组合值的顺序,则可以使用.com()方法

combo remember that it count from 0, as this script show. 组合记住该脚本从0开始计数。

Select an item from the combobox and see what happend. 从组合框中选择一个项目,然后查看发生了什么。

 #!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

class App(tk.Tk):
    """Docstring about this class"""

    def __init__(self):
        super().__init__()

        self.protocol("WM_DELETE_WINDOW", self.on_exit)
        s = "{0}".format('Simple App')
        self.title(s)

        self.values = ('Engine', 'Network','Apple','Banana','Orange','Grapes','Watermelon','Plum','Strawberries','Pear')

        self.selected_data = tk.StringVar()


        self.init_ui()

    def init_ui(self):

        f = ttk.Frame()

        ttk.Label(f, text = "Combobox").pack()
        self.cbCombo = ttk.Combobox(f,state='readonly',values=self.values)
        self.cbCombo.bind("<<ComboboxSelected>>", self.on_selected)
        self.cbCombo.pack()

        ttk.Label(f, textvariable = self.selected_data).pack()

        w = ttk.Frame()

        ttk.Button(w, text="Callback", command=self.on_callback).pack()
        ttk.Button(w, text="Reset", command=self.on_reset).pack()
        ttk.Button(w, text="Exit", command=self.on_exit).pack()

        f.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)


    def on_selected(self, evt=None):

         if self.cbCombo.current() != -1:

              msg = "You have selected:\n{0} {1}".format(self.cbCombo.current(), self.cbCombo.get())

              self.selected_data.set(msg)

    def on_callback(self,):

        if self.cbCombo.current() != -1:

            msg = "You have selected:\n{0} {1}".format(self.cbCombo.current(), self.cbCombo.get())
        else:
            msg = "You did not select anything"

        messagebox.showinfo(self.title(), msg)

    def on_reset(self):
        self.cbCombo.set('')


    def on_exit(self):
        """Close all"""
        if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
            self.destroy()               

if __name__ == '__main__':
    app = App()
    app.mainloop()

在此处输入图片说明

You can make use of the <<ComboboxSelected>> event to know what item has been selected. 您可以利用<<ComboboxSelected>>事件来知道已选择了哪个项目。

Alternatively, use combobox::current to get the index of the currently selected item, and combobox::get to get the value 或者,使用combobox::current获取当前所选项目的索引,并使用combobox::get获取值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM