Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

python - Finding the lowest number that does not occur at the end of a string, in a tuple in a list

I have a list of tuples, each has a single string as element 0, in these strings I want to get out the final number, and then find the lowest (positive) number that is not in this list.

How do you do this?

E.g. for the list tups:

tups=[('.p1.r1.c2',),('.p1.r1.c4',),('.p1.r1.c16',)]

the final numbers are 2, 4 and 16, so the lowest unused number is 1.


my attempt was this:

tups2= [tup[0] for tup in tups]         # convert tuples in lists to the strings with information we are interested in
tups3 = [tup .rfind("c") for tup in tups2] # find the bit we care about

I wasn't sure how to finish it, or if it was fast/smart way to proceed


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You didn't really specify your problem but I'm guessing that getting the lowest unused number is the issue. the solutions above is great but it just gets the lowest number in the list and not the lowest unused one. I tried to make a list of all the unused numbers then getting the minimum value of it.

I hope that would help

tups=[('15.p1.r1.c2',),('.poj1.r1.c4',),('.p2.r4.c160',)]
numbers = []
unused_numbers = []
for tup in tups:
    words = tup[0].strip(".").split('.')
    digits_list = [''.join(x for x in i if x.isdigit()) for i in words]
    unused_numbers.extend(digits_list[:-1])
    numbers.append(digits_list[-1])
print(numbers)
print(min(unused_numbers))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...