如何从python

时间:2017-12-14 05:53:40

标签: 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中做到这一点

预期输出

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 个答案:

答案 0 :(得分:2)

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

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

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

相关问题