假设
list1 = [['a', (1, 1)], ['a', (1, 3)], ['a', (1, 4)], ['b', (2,1)], ['b', (2,2)], ['b',(2, 4)]]
list2 = [[(1, 1), (1, 3), (2, 1), (2, 2), (2, 4)]]
现在我怎么能为list1报告错误['b',(1,2)]缺失或['b',(2,3)]缺失
同样对于list2,应该有报告错误(1,2)或(2,3)缺失
我的意图是报告错误,例如,如果序列中缺少某些内容,如(1,1)然后来(1,2)后跟(1,3)如果(1,2)缺失则错误
答案 0 :(得分:0)
您应该使用dict而不是列表。但这是使用您的结构的解决方案。 s1
与上一个答案类似,但注意到不必要的长列表理解以获得list1
中的模式。并且您需要使用特定的for循环来检查而不是设置“-
”运算符。
>>> s1 = [[x, (c, d)] for x in ['a', 'b']
... for c in range(1, 3)
... for d in range(1, 5)
... if x=='a' and c==1 or x=='b' and c==2]
>>> s1
[['a', (1, 1)], ['a', (1, 2)], ['a', (1, 3)], ['a', (1, 4)],
['b', (2, 1)], ['b', (2, 2)], ['b', (2, 3)], ['b', (2, 4)]]
>>>
>>> list1 = [['a', (1, 1)], ['a', (1, 3)], ['a', (1, 4)],
... ['b', (2, 1)], ['b', (2, 2)], ['b', (2, 4)]]
>>> for thing in s1:
... if thing not in list1:
... print 'missing: ', thing
... # or raise an error if you want
...
missing: ['a', (1, 2)]
missing: ['b', (2, 3)]
对list2
重复相同的操作。使用上面的s2
示例,可以更轻松地创建s1
。
顺便说一下,list1
的dict看起来像这样:
dict1 = {'a': [(1, 1), (1, 3), (1, 4)], 'b': [(2, 1), (2, 2), (2, 4)]}
然后创建s1会稍微简化,但比较循环可能会延长两行。
要回答概括的问题,然后 1。首先知道字母或 2。知道数字/字母数量?
知道信件:
>>> set_of_letters = ('a', 'b', 'c')
>>> s1 = [[x, (ord(x)-96, d)]
... for x in set_of_letters
... for d in range(1, 5)]
>>> s1
[['a', (1, 1)], ['a', (1, 2)], ['a', (1, 3)], ['a', (1, 4)],
['b', (2, 1)], ['b', (2, 2)], ['b', (2, 3)], ['b', (2, 4)],
['c', (3, 1)], ['c', (3, 2)], ['c', (3, 3)], ['c', (3, 4)]]
了解数字:
>>> number_of_letters = 3
>>> s1 = [[chr(c+96), (c, d)]
... for c in range(1, number_of_letters + 1)
... for d in range(1, 5)]
>>> s1
[['a', (1, 1)], ['a', (1, 2)], ['a', (1, 3)], ['a', (1, 4)],
['b', (2, 1)], ['b', (2, 2)], ['b', (2, 3)], ['b', (2, 4)],
['c', (3, 1)], ['c', (3, 2)], ['c', (3, 3)], ['c', (3, 4)]]
答案 1 :(得分:0)
from collections import defaultdict
set1 = set(list1)
set2 = set(list2)
missing = []
dict1 = defaultdict(lambda: defaultdict(list))
dict2 = defaultdict(list)
for key, sublist in set1:
dict1[key][sublist[0]].append(sublist[1])
for key, value in set2:
dict2[key].append(value)
for key, subdict in sorted(dict1.iteritems()):
for subkey, values in sorted(subdict.iteritems()):
subkey_misses = []
last_value = None
for value in values:
if last_value is not None and last_value + 1 != value:
subkey_misses.extend(range(last_value + 1, value))
last_value = value
if subkey_misses:
misses.append('%s.%d missing %s' % (key, subkey, subkey_misses))
for key, values in sorted(dict2.iteritems()):
key_misses = []
last_value = None
for value in values:
if last_value is not None and last_value + 1 != value:
key_misses.append(range(last_value + 1), value))
last_value = value
if key_misses:
misses.append('%d missing %s' % (key, key_misses))
print misses