用Python中的map()函数格式化

2024-10-02 00:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写代码将马赫数转换成英尺/秒,我想用lambda操作符的map函数来转换它。我有一个参数,叫做machList。我可以成功地转换,但我有麻烦格式化它正确,所以答案不出来作为整个列表转换的答案。你知道吗

到目前为止,我的代码如下所示:

def machToFPS(machList):
    for x in machList:   
        FPS = map(lambda x: x*1116.4370079,machList)        
        print('{0}'.format(x), "mach(s) is equivalent to",FPS, "feet per second.")

如果machList=[1,5,3],我得到的输出是:

1 mach(s) is equivalent to [1116.4370079, 5582.1850395, 3349.3110237] feet per second.

5 mach(s) is equivalent to [1116.4370079, 5582.1850395, 3349.3110237] feet per second.

3 mach(s) is equivalent to [1116.4370079, 5582.1850395, 3349.3110237] feet per second.

I want my answer to look like this:

1 mach is equivalent    to      1116.4370079        feet    per second.

5       mach    is  equivalent  to      5582.1850395        feet    per second.

3       mach    is  equivalent  to      3349.3110237        feet    per second.

有人能帮我吗?map()函数把我搞砸了。你知道吗


Tags: tolambda函数答案代码map参数is
3条回答

map(function, arg_list)返回一个列表,其中包含使用数组arg_list的每个元素调用function的结果。您需要迭代map调用的结果。你知道吗

一种方法是让lambda函数返回一个元组:

def mach_to_fps(mach_list):
    # Returning a tuple from the lambda allows the print to get all of its information
    # from the contents of the return list alone.
    for mach_fps_tuple in map(lambda mach: (mach, mach * 1116.4370079), mach_list):
        # *mach_fps_tuple breaks the tuple out into separate arguments for format.
        # Using old-style format would look like this:
        #    'mach(%s) is equivalent to %s feet per second' % mach_fps_tuple
        print('mach({0}) is equivalent to {1} feet per second'.format(*mach_fps_tuple))

mach_to_fps([1, 5, 3])

$ python mach.py
mach(1) is equivalent to 1116.4370079 feet per second
mach(5) is equivalent to 5582.1850395 feet per second
mach(3) is equivalent to 3349.3110237 feet per second

注意,我使用PEP8格式化了它,这是强烈推荐的。你知道吗

如果need要使用map函数,则:

machList = [1,5,3]

def machToFPS(machList):
    FPS = map(lambda x: x*1116.4370079,machList) 
    for i,x in enumerate(FPS):
        print('{} mach(s) is equivalent to {} feet per second.'.format(machList[i], x))

machToFPS(machList)

如果没有,就按照下一个答案中显示的那样做(只使用for循环)。你知道吗

输出:

1 mach(s) is equivalent to 1116.4370079 feet per second.
5 mach(s) is equivalent to 5582.1850395 feet per second.
3 mach(s) is equivalent to 3349.3110237 feet per second.

您不需要使用map函数。事实上,使用它是导致这个问题的原因。你知道吗

machList上迭代时,x等于machList列表中的单个项。你知道吗

所以x是一个整数1、3或5。你知道吗

所以你要做的就是:

def machToFPS(machList):
  for x in machList
    FPS = x * 1116.4370079
    print('{0}'.format(x), "mach(s) is equivalent to",FPS, "feet per second.")

这样就可以输出你想要的文本了。你知道吗

为了使用map函数获得相同的输出,可以执行以下操作:

def machToFPS(machList):
  fpsList = map(lambda x: x*1116.4370079,machList)
  for x in fpsList
    print('{0}'.format(x), "mach(s) is equivalent to",FPS, "feet per second.")

相关问题 更多 >

    热门问题