您应该使用字典而不是列表。但这是使用您的结构的解决方案。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
:
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)]]