reduction
Steven D'Aprano
steve at pearwood.info
Tue May 31 11:24:22 EDT 2016
On Wed, 1 Jun 2016 12:22 am, Fillmore wrote:
>
> My problem. I have lists of substrings associated to values:
>
> ['a','b','c','g'] => 1
> ['a','b','c','h'] => 1
> ['a','b','c','i'] => 1
> ['a','b','c','j'] => 1
> ['a','b','c','k'] => 1
> ['a','b','c','l'] => 0 # <- Black sheep!!!
> ['a','b','c','m'] => 1
> ['a','b','c','n'] => 1
> ['a','b','c','o'] => 1
> ['a','b','c','p'] => 1
Are the first three items always the same? If so, they're pointless, and get
rid of them.
'g' => 1
'h' => 1
'i' => 1
...
is best stored as a dict.
If not, well, does 'l' *always* represent 0? In other words:
['a','b','c','l'] => 0
['a','b','d','l'] => 0
['x','y','z','l'] => 0
...
then it sounds like you need a dict storing each letter individually:
d = {'a': 1, 'b': 1, 'c': 1, 'l': 0}
for letter in ['a','b','c','l']:
if d[letter] == 0:
print("Black sheep")
break
which can be written more compactly as:
if not all(d[letter] for letter in 'abcl'):
print("Black sheep")
If your items actually are letters, then you can reduce the fiddly typing
with something a bit easier:
# instead of
# d = {'a': 1, 'b': 1, 'c': 1, 'l': 0}
letters = 'abcdefghijklmno'
bits = '111111111110111'
d = {k: int(b) for k, b in zip(letters, bits)}
--
Steven
More information about the Python-list
mailing list