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

标签 python listview tkinter listbox

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

Priorities

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

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

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 3.5 开始,可以添加 type hints 。加上dataclasses (Python 3.7+)和generic collections (Python 3.9+),你可以这样写:

from dataclasses import dataclass


@dataclass
class Priority:
    """Basic example class"""
    name: str
    level: int = 1


foo = Priority("foo")
bar = Priority("bar", 2)

priorities: list[Priority] = [foo, bar]

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2)]
print(sorted(priorities, key= lambda p: p.name))
# [Priority(name='bar', level=2), Priority(name='foo', level=1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2), 'Not a priority']

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

from typing import List


class Priority:
    """Basic example class"""
    def __init__(self, name: str, level: int = 1):
        self.name = name
        self.level = level

    def __str__(self):
        return '%s (%d)' % (self.name, self.level)

    def __repr__(self):
        return str(self)


foo = Priority("foo")
bar = Priority("bar", 2)

priorities: List[Priority] = [foo, bar]

print(priorities)
# [foo (1), bar (2)]
print(sorted(priorities, key=lambda p: p.name))
# [bar (2), foo (1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [foo (1), bar (2), 'Not a priority']

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

您可以使用 mypy 显式检查错误:

❯ mypy priorities.py
priorities.py:22: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "Priority"
Found 1 error in 1 file (checked 1 source file)

动态语言

即使现在有类型提示,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']]

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

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

所以如果你想要相当于:

List<Priority> priorities

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

关于C# 通用 List<T> 的 Python 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168350/

相关文章:

python - 按一列分组并在另一列中唯一

python - 如何在 Django 中上传文件并显示进度条?

python - 行李箱工作标签没有吗? ---导入错误: No module named 2. 1.2

python - Pandas Date Format 不转换日期

Android ListView 背景

android - ListView 不刷新 fragment 与 viewpager 选项卡

python - 激活的元素和选定的元素有什么区别?

python - 将文本应用到两个 tkinter RadioButton

javascript - React Native ListView TextInput 锁定性能优化渲染

python - Tkinter 导致 SIGSEGV 和系统崩溃 - 如何修复?