C# 通用 List<T> 的 Python 等效项

wra*_*h46 5 python listview listbox tkinter

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

优先事项

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

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

List<Priority> priorities = new List<Priority>();
Run Code Online (Sandbox Code Playgroud)

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

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();

}
Run Code Online (Sandbox Code Playgroud)

Eri*_*nil 4

类型提示

\n

从 Python 3.5 开始,可以添加类型提示。结合数据类(Python 3.7+) 和泛型集合(Python 3.9+),您可以编写:

\n
from dataclasses import dataclass\n\n\n@dataclass\nclass Priority:\n    """Basic example class"""\n    name: str\n    level: int = 1\n\n\nfoo = Priority("foo")\nbar = Priority("bar", 2)\n\npriorities: list[Priority] = [foo, bar]\n\nprint(priorities)\n# [Priority(name=\'foo\', level=1), Priority(name=\'bar\', level=2)]\nprint(sorted(priorities, key= lambda p: p.name))\n# [Priority(name=\'bar\', level=2), Priority(name=\'foo\', level=1)]\n\nbaz = "Not a priority"\npriorities.append(baz) # <- Your IDE will probably complain\n\nprint(priorities)\n# [Priority(name=\'foo\', level=1), Priority(name=\'bar\', level=2), \'Not a priority\']\n
Run Code Online (Sandbox Code Playgroud)\n

在 Python 3.5 中,代码如下所示:

\n
from typing import List\n\n\nclass Priority:\n    """Basic example class"""\n    def __init__(self, name: str, level: int = 1):\n        self.name = name\n        self.level = level\n\n    def __str__(self):\n        return \'%s (%d)\' % (self.name, self.level)\n\n    def __repr__(self):\n        return str(self)\n\n\nfoo = Priority("foo")\nbar = Priority("bar", 2)\n\npriorities: List[Priority] = [foo, bar]\n\nprint(priorities)\n# [foo (1), bar (2)]\nprint(sorted(priorities, key=lambda p: p.name))\n# [bar (2), foo (1)]\n\nbaz = "Not a priority"\npriorities.append(baz) # <- Your IDE will probably complain\n\nprint(priorities)\n# [foo (1), bar (2), \'Not a priority\']\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,类型提示是可选的,即使附加时存在类型不匹配,上述代码也将正常运行baz

\n

您可以使用以下命令显式检查错误mypy

\n
\xe2\x9d\xaf mypy priorities.py\npriorities.py:22: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "Priority"\nFound 1 error in 1 file (checked 1 source file)\n
Run Code Online (Sandbox Code Playgroud)\n

动态语言

\n

即使现在有类型提示,Python 仍然保持动态,并且类型提示是完全可选的:

\n
>>> my_generic_list = []\n>>> my_generic_list.append(3)\n>>> my_generic_list.append("string")\n>>> my_generic_list.append([\'another list\'])\n>>> my_generic_list\n[3, \'string\', [\'another list\']]\n
Run Code Online (Sandbox Code Playgroud)\n

在将任何对象附加到现有列表之前,您不必定义任何内容。

\n

Python 使用鸭子类型。如果您迭代列表并对每个元素调用方法,则需要确保元素理解该方法。

\n

所以如果你想要相当于:

\n
List<Priority> priorities\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

  • @gabrielgarcia:如果你想明确检查,你可以使用Python [类型提示](https://docs.python.org/3/library/typing.html)。例如:`从输入 import List; Vector = List[float];def scale(标量: float, 矢量: Vector) -&gt; 矢量:...` (2认同)