0

Really stuck here and need some advice please....

I have a list ...

transposedlist = [('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('-', '*', '*', '*'), ('1', '3', '3', '*'), ('-', ' ', ' ', '*'), 

each group in the transposedlist above represents a column in a Matrix.

I would like to delete any group which contains NO numbers.

Heres my attempt thus far...

for i, group in enumerate(Listoflists):
    if "-" in group[1:] == group[:-1] or "*" in group[1:] == group[:-1] or group[1:] None == group[:1]:
        Matrix.DeleteColumn(i)

The code above checks of the 1st item is the same as the last item in the group, if it is then it should delete the column, this is not ideal obviously because it ignores the items in the middle.

Any suggestions?

4

3 回答 3

0

Try a list-comprehension:

>>> transposedlist = [('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('-', '*', '*', '*'), ('1', '3', '3', '*'), ('-', ' ', ' ', '*')]
>>> newlist = [x for x in transposedlist if any(y.isdigit() for y in x)]   
>>> newlist
[('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('1', '3', '3', '*')]
>>>

If you want to read more, here are references on any and str.isdigit

于 2013-10-25T16:12:03.413 回答
0

Use the any() function with a list comprehension to keep entries with numbers instead:

transposedlist = [entry for entry in transposedlist if any(e.isdigit() for e in entry)]

The any() function here returns True if there is any value in the iterable (a generator expression here) that is True, False otherwise. If the expression (e.isdigit() for e in entry) only yields False then that entry will not be included in the new list.

Demo:

>>> transposedlist = [('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('-', '*', '*', '*'), ('1', '3', '3', '*'), ('-', ' ', ' ', '*')]
>>> any(e.isdigit() for e in transposedlist[0])
True
>>> any(e.isdigit() for e in transposedlist[3])
False
>>> [entry for entry in transposedlist if any(e.isdigit() for e in entry)]
[('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('1', '3', '3', '*')]
于 2013-10-25T16:12:08.880 回答
0
import re
import string

transposedlist = [('-', '*', '*', '1'), ('7', '6', '6', '1'), ('-', '*', '1', '*'), ('-', '*', '*', '*'), ('1', '3', '3', '*'), ('-', ' ', ' ', '*')]

newlist = [x for x in transposedlist if re.search("[0-9]",string.join(x,"")) is not None]
于 2013-10-25T16:21:45.707 回答