Skip to main content
 首页 » 编程设计

python之如何从python中的列表中分类各种类别

2024年10月01日7mfryf

我在列表中有一个数据如下

   ['And user clicks on the link "Statement and letter preferences" -> set([0, 2])', 
   'And user waits for 10 seconds -> set([0, 2])', 
   'Then page is successfully launched -> set([0, 1, 2])', 
   '@TestRun -> set([0, 1, 2])', 
   'And user set text "#Surname" on textbox name "surname" -> set([0, 1, 2])', 
   'And user click on "menu open user preferences" label -> set([0, 2])'] 

在我设置的这些数据中([0,2]),现在我想要在不同列表中出现在 0,1,2 中的所有语句? 我们如何在 python 中做到这一点

预期输出是

list_0 即包含在 set(0,2) 中具有 0 的所有语句

 list_0      
  [And user clicks on the link "Statement and letter preferences 
   And user waits for 10 seconds 
   Then page is successfully launched 
  '@TestRun  
   And user set text "#Surname" on textbox name "surname 
   And user click on "menu open user preferences" label] 
 
 list_1 
  [ Then page is successfully launched 
  '@TestRun  
   And user set text "#Surname" on textbox name "surname] 
 
  list_2 
 [And user clicks on the link "Statement and letter preferences 
   And user waits for 10 seconds 
   Then page is successfully launched 
  '@TestRun  
   And user set text "#Surname" on textbox name "surname 
   And user click on "menu open user preferences" label] 

请您参考如下方法:

我建议将字符串附加到列表字典中。你会明白为什么的。

首先,这是解决此问题的高级方法 -

  1. 遍历每个字符串
  2. 将字符串拆分为其内容和 ID 列表
  3. 对于每个 ID,将字符串添加到相应的字典键中。
from collections import defaultdict 
import re 
 
d = defaultdict(list) 
 
for i in data: 
    x, y = i.split('->') 
    for z in  map(int, re.findall('\d+', y)): 
        d[z].append(x.strip())  # for performance, move the `strip` call outside the loop 
print(d) 
{ 
    "0": [ 
        "And user clicks on the link \"Statement and letter preferences\"", 
        "And user waits for 10 seconds", 
        "Then page is successfully launched", 
        "@TestRun", 
        "And user set text \"#Surname\" on textbox name \"surname\"", 
        "And user click on \"menu open user preferences\" label" 
    ], 
    "1": [ 
        "Then page is successfully launched", 
        "@TestRun", 
        "And user set text \"#Surname\" on textbox name \"surname\"" 
    ], 
    "2": [ 
        "And user clicks on the link \"Statement and letter preferences\"", 
        "And user waits for 10 seconds", 
        "Then page is successfully launched", 
        "@TestRun", 
        "And user set text \"#Surname\" on textbox name \"surname\"", 
        "And user click on \"menu open user preferences\" label" 
    ] 
} 

通过查询d[i]可以找到所有与IDi相关的字符串。这比初始化单独的列表要干净得多。