set([0, 2])', -6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:22 27 4
gpt4 key购买 nike

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

   ['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相关的字符串。这比初始化单独的列表要干净得多。

关于python - 如何从python中的列表中分类各种类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47806699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com