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
567 views
in Technique[技术] by (71.8m points)

python - Given a list of triples, return a list with the second element of each triple (If an item is not a triple, return None for that element )

I have to use doctest to run and check the following

>>> extract_second([('a',3,'x'),('b',4,'y')])     
[3, 4]

I was able to run this successfully using :

x[1] for x in elements

but the second test was not successful which is:

>>> extract_second([('c',5,'z'),('d',6)])
[5, None]

then i used the following code to work it out by a little bit research

lst=[(1,2,3),(4,5,6)]

for i in lst:
    if len(i) != 3:
        print "None"
    else:
        print i[1],

Earlier I was able to print the output as required but brackets and comma was not included in it

Expected outcome:

[3,4]
[5, None]

Received output:

3 4
5 None
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You are printing in the loop rather than constructing a new list:

result = []
for i in lst:
    if len(i) != 3:
        result.append(None)
    else:
        result.append(i[1])
return result

Should give you the expected output.

Note: you could still do this with a list comprehension:

>>> elements = [('c',5,'z'),('d',6)]
>>> [x[1] if len(x) == 3 else None for x in elements]
[5, None]

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

...