Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

dictionary - How do I make Maps and lambdas work with a matrix in python 3.4?

I often avoid me to write posts like this but I'm new in python 3.4 and I need a help with this code.

Suppose we have the following list:

v = [ [ x, y ] for x in ['a','b','c'] for y in range(1,5) ]

It results a list of lists: [ ['a', '1'], ['a','2'], ... ]

Now I'd want to join those string. I've tried the following:

p = map(lambda (x, y): ''.join(x,y), v)

It didn't work.

The error:

TypeError: join() takes exactly one argument (2 given)

I've tried to look up in the documentation But I coudn't solve my problem though.

Does someone have some idea?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can do:

>>> list(map(lambda x: ''.join(map(str, x)), v))
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']

This executes the function lambda x: ''.join(map(str, x)) for each element in v. An element in v is a list with one string and one integer as values. This means x, as received by the lambda function, is a list with those two values.

We then need to ensure all values in that list are strings before passing them to join(). This means we'll call map(str, x) to turn all values in the sublist x into strings (['a', 1] becomes ['a', '1']). We can then join them by passing the result of that to ''.join(...) (['a', '1'] becomes ['a1']). This is done for each list in v so this gives us the desired result.

The result of map is a so-called mapobject in Python 3.x so we wrapped everything in a list() call to end up with a list.

Also, a list comprehension is arguably more readable here:

>>> [x[0] + str(x[1]) for x in v]
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...