给出一个列表,说[4,5,6,7]我想编写一个将输出的函数 所有对([4,5,7],[6]),([4,5],[6,7]) 子列表的长度不固定
我使用了一个for循环和两个新列表来将第ith个元素追加到列出一个 并将其余的附加到列表2中,然后重复该过程,我知道这是一种愚蠢的方法
a = [4,5,6,7]
for x in range(0,len(a)):
b = []
c = []
b.append(a[x])
for y in range(0,len(a)):
if y!=x:
c.append(a[y])
print(b,c)
for x in range(0,len(a)-1):
b = []
c = []
b.append(a[x])
b.append(a[x+1])
for y in range(0,len(a)):
if y!=x and y!=x+1:
c.append(a[y])
print(b,c)
我希望打印所有可能的子列表,但始终会错过不连续的子列表,我会得到([4,5],[6,7])但从不生成 ([4,6],[5,7])
答案 0 :(得分:1)
您可以使用itertools模块来构造所有此类子列表:
import itertools as it
s = {4,5,6,7}
for length in range(len(s)):
for combination in it.combinations(s, length):
print(list(combination), list(s - set(combination)))
[] [4, 5, 6, 7] [4] [5, 6, 7] [5] [4, 6, 7] [6] [4, 5, 7] [7] [4, 5, 6] [4, 5] [6, 7] [4, 6] [5, 7] [4, 7] [5, 6] [5, 6] [4, 7] [5, 7] [4, 6] [6, 7] [4, 5] [4, 5, 6] [7] [4, 5, 7] [6] [4, 6, 7] [5] [5, 6, 7] [4]
答案 1 :(得分:1)
这是不删除重复项的解决方案:
from itertools import combinations
a = [4,4,5,6,7]
result = []
for x in range(len(a) + 1):
for left in combinations(a, x):
right = a.copy()
for ele in left:
right.remove(ele)
result.append([list(left), right])
for res in result:
print(res)
输出:
[[], [4, 4, 5, 6, 7]]
[[4], [4, 5, 6, 7]]
[[4], [4, 5, 6, 7]]
[[5], [4, 4, 6, 7]]
[[6], [4, 4, 5, 7]]
[[7], [4, 4, 5, 6]]
[[4, 4], [5, 6, 7]]
[[4, 5], [4, 6, 7]]
[[4, 6], [4, 5, 7]]
[[4, 7], [4, 5, 6]]
[[4, 5], [4, 6, 7]]
[[4, 6], [4, 5, 7]]
[[4, 7], [4, 5, 6]]
[[5, 6], [4, 4, 7]]
[[5, 7], [4, 4, 6]]
[[6, 7], [4, 4, 5]]
[[4, 4, 5], [6, 7]]
[[4, 4, 6], [5, 7]]
[[4, 4, 7], [5, 6]]
[[4, 5, 6], [4, 7]]
[[4, 5, 7], [4, 6]]
[[4, 6, 7], [4, 5]]
[[4, 5, 6], [4, 7]]
[[4, 5, 7], [4, 6]]
[[4, 6, 7], [4, 5]]
[[5, 6, 7], [4, 4]]
[[4, 4, 5, 6], [7]]
[[4, 4, 5, 7], [6]]
[[4, 4, 6, 7], [5]]
[[4, 5, 6, 7], [4]]
[[4, 5, 6, 7], [4]]
[[4, 4, 5, 6, 7], []]
答案 2 :(得分:0)
您可以创建一个随机子列表,然后获取第二个列表中不属于该随机子列表的元素:
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"identifier:(\s+)?(.*?)(\s+)?\]"
test_str = ("OBNAME[origin:85 copy:1 identifier:TDEP],OBNAME[origin:85 copy:1 identifier:RDEP]\n\n"
"OBNAME[origin:85 copy:1 identifier: TDEP ],OBNAME[origin:85 copy:1 identifier: RDEP ]")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
关于如何将原始列表划分为随机块,具体取决于您解决