我正在创建一个简单的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();} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 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实例即可。而已! (adsbygoogle = window.adsbygoogle || []).push({});
10-01 22:28
查看更多