【问题标题】:Python equivalent for C#'s generic List<T>C# 的通用 List<T> 的 Python 等效项
【发布时间】:2017-08-27 08:36:33
【问题描述】:

我正在创建一个简单的 GUI 程序来管理优先级。

我已经成功地添加了将项目添加到列表框的功能。现在我想将该项目添加到 C# 中称为 List 的内容中。 Python中有这样的东西吗?

例如,在 C# 中,要向列表视图中添加一个项目,我首先要创建:

List<Priority> priorities = new List<Priority>();

...然后创建以下方法:

void Add()
{
    if (listView1.SelectedItems.Count > 0)
    {
        MessageBox.Show("Please make sure you have no priorities selected!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else if (txt_Priority.ReadOnly == true) { MessageBox.Show("Please make sure you refresh fields first!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
    else
    {
        if ((txt_Priority.Text.Trim().Length == 0)) { MessageBox.Show("Please enter the word!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
        else
        {
            Priority p = new Priority();
            p.Subject = txt_Priority.Text;

            if (priorities.Find(x => x.Subject == p.Subject) == null)
            {
                priorities.Add(p);
                listView1.Items.Add(p.Subject);
            }
            else
            {
                MessageBox.Show("That priority already exists in your program!");
            }
            ClearAll();
            Sync();
            Count();
        }
    }
    SaveAll();

}

【问题讨论】:

  • 而你在搜索“Python 列表”时找不到任何信息?!

标签: python listview tkinter listbox


【解决方案1】:

Python 是 dynamic

>>> my_generic_list = []
>>> my_generic_list.append(3)
>>> my_generic_list.append("string")
>>> my_generic_list.append(['another list'])
>>> my_generic_list
[3, 'string', ['another list']]

在将 any 对象附加到现有的 list 之前,您无需定义任何内容。

Python 使用duck-typing。如果您在列表上进行迭代并在每个元素上调用方法,则需要确保元素理解该方法。

所以如果你想要相当于:

List<Priority> priorities

您只需要初始化一个列表并确保您只向其中添加Priority 实例。就是这样!

【讨论】:

  • 强制列表成为一个类型怎么样?我是否需要创建一个带有append 方法的类,当类型不是应该的类型时会引发异常?
  • @gabrielgarcia:如果你想明确地检查,你可以使用 Python type hints。例如:from typing import List; Vector = List[float];def scale(scalar: float, vector: Vector) -&gt; Vector:...
【解决方案2】:

幸运的是,从 Python 3.9 (3.8) 开始支持泛型集合:https://docs.python.org/3/library/typing.html#generic-concrete-collections
这是一个例子:

listOfInts: list[int] = []

# dictionary with string keys and int values:
typedDict: dict[str, int] = []

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2021-07-12
    • 2011-03-30
    • 1970-01-01
    • 2023-03-23
    • 2010-10-24
    • 1970-01-01
    • 2015-11-05
    • 2015-05-28
    相关资源
    最近更新 更多