如何在python中从列表中分类

2024-05-15 15:13:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据列表如下

   ['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中做到这一点

预期输出为

列出0,即包含集合(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]

Tags: andtextnameisonpagesurnametestrun
1条回答
网友
1楼 · 发布于 2024-05-15 15:13:17

我建议在列表字典中附加字符串。你会明白为什么的。你知道吗

首先,这里有一个高层次的方法来解决这个问题-

  1. 迭代每个字符串
  2. 将字符串拆分为其内容和ID列表
  3. 对于每个ID,将字符串添加到相应的dict键。你知道吗
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相关的所有字符串。这比初始化单独的列表要干净得多。你知道吗

相关问题 更多 >