Python:如何在列表中获取包含方括号的元素(列表中的列表)

时间:2018-02-05 03:00:31

标签: python string list square-bracket

我尝试从' list'中生成新列表,例如

['I','want','[to,you]','go','to','[park,school]']

*对不起,我想将参考列表更新为

['I','want','['to','you']','go','to','['park','school']']

我想要的输出是

['I','want','to,','go','to','park']
['I','want','you,','go','to','park']
['I','want','to,','go','to','school']
['I','want','you,','go','to','school']

但我仍然无法找到包含' ['。

的元素

我尝试编码:if any("abc" in s for s in some_list):

你确实知道这个案子吗?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

import re
import itertools
s = ['I','want','[to,you]','go','to','[park,school]']
new_s = [i if not i.startswith('[') and not i.endswith(']') else re.findall('[a-zA-Z]+', i) for i in s]
lists = filter(lambda x:isinstance(x, list), new_s)
combos = [(a, b) for a, b in itertools.combinations([i for b in lists for i in b], 2) if a in lists[0] and b in lists[1]]
final_results = sorted([[next(i) if b.startswith('[') else b for b in s] for i in map(iter, combos)], key=lambda x:x[-1])

输出:

[['I', 'want', 'to', 'go', 'to', 'park'],
 ['I', 'want', 'you', 'go', 'to', 'park'], 
 ['I', 'want', 'to', 'go', 'to', 'school'], 
 ['I', 'want', 'you', 'go', 'to', 'school']]

答案 1 :(得分:1)

使用itertools.product

的一种方法
from itertools import product
lst_eval = [(i, j[1:-1].split(',')) if j.startswith('[') else j for i,j in enumerate(mylist)]
idx, lst = zip(*[l for l in lst_eval if isinstance(l, tuple)])
for p in product(*lst):
    for i, v in zip(idx, p):
        mylist[i] = v
    print (mylist)

输出:

['I', 'want', 'to', 'go', 'to', 'park']
['I', 'want', 'to', 'go', 'to', 'school']
['I', 'want', 'you', 'go', 'to', 'park']
['I', 'want', 'you', 'go', 'to', 'school']

答案 2 :(得分:0)

不要'真的了解你的代码。 但 '[to,you]'是一个字符串

尝试

if str[0]=='[' and str[-1] == ']':
     strList = str[1,-1].split(,)

获取内部列表