我的列表中的数据如下
['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]
答案 0 :(得分:2)
我建议将字符串附加到列表字典中。你会明白为什么。
首先,这是解决此问题的高级方法 -
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"
]
}
您可以通过查询i
找到与ID d[i]
相关的所有字符串。这比初始化单独的列表要清晰得多。