如何使用python 3.4中的“map”和“lambdas”使用矩阵? [英] How do I make Maps and lambdas work with a matrix in python 3.4?

查看:710
本文介绍了如何使用python 3.4中的“map”和“lambdas”使用矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常避免我写这样的帖子,但是我在python 3.4中是新的,我需要这个代码的帮助。



假设我们有以下列表:

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

它会列出一个列表:[['a' ,'1'],['a','2'],...]



现在我想加入这些字符串。我尝试了以下内容:

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

它没有工作。



错误:

  TypeError:join()只需一个参数(给定2)

我试图查找文档但是我无法解决我的问题。



有人有一些想法吗?

解决方案

您可以:

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

v 中的每个元素执行函数 lambda x:''.join(map(str,x)) code>。 v 中的元素是一个包含一个字符串和一个整数作为值的列表。这意味着 lambda 函数收到的 x 是具有这两个值的列表。



然后,我们需要确保该列表中的所有值都是字符串,然后再将它们传递给 join()。这意味着我们将调用 map(str,x)将子列表 x 中的所有值转换为字符串( ['a',1] 成为 ['a','1'] )。我们可以通过将结果传递给''来加入它们。join(...) ['a','1'] 成为 ['a1'] )。这是为 v 中的每个列表完成的,所以这给了我们所需的结果。



map 是Python 3.x中所谓的 mapobject ,所以我们把所有内容都包含在一个 list() 调用结束一个列表。



另外,一个列表的理解可以在这里更可读:

 >>>对于v中的x] 
['a1','a2','a3','a4','b1','b2','b3'的[x [0] + str(x [1] ,'b4','c1','c2','c3','c4']


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?

解决方案

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']

这篇关于如何使用python 3.4中的“map”和“lambdas”使用矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆