通过函数运行数字范围

时间:2015-11-18 11:13:44

标签: python

所以我创建了一系列数字,我希望通过一个函数运行数字列表,这样我就可以得到多个数字。

x = range(1,6)

def fun(x):
    x**2 + x + 2

这是基本的想法。但我无法弄清楚如何一次一个地运行列表中的各个元素,所以我可以输出5个(对于这个例子)。

4, 8, 14, 22, 32

5 个答案:

答案 0 :(得分:3)

map function的作用是什么:

  

map(function, iterable, ...)

     

将函数应用于iterable的每个项目并返回结果列表。如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地应用于所有迭代的项。如果一个iterable比另一个短,则假定使用None项扩展。如果function为None,则假定为identity函数;如果有多个参数,map()返回一个由包含所有迭代中相应项的元组组成的列表(一种转置操作)。可迭代参数可以是序列或任何可迭代对象;结果总是一个列表。

你可以在基本上每种编程语言中找到它或它的变体。

map(fun, range(1,6))

或者,您可以使用list comprehension

[fun(x) for x in range(1,6)]

答案 1 :(得分:2)

您可以使用map在列表的每个元素上应用函数:

li = range(1, 6)

def fun(x):
   return x**2 + x + 2

print map(fun, li)
>> [4, 8, 14, 22, 32]

如果使用Python 3,则需要将返回值从map转换为列表:

print list(map(fun, li))
>> [4, 8, 14, 22, 32]

答案 2 :(得分:0)

通常,从一个列表到另一个列表执行一对一转换的首选方法是使用列表推导。

for key in StockDict.keys():
AttributeError: 'function' object has no attribute 'keys'

它也适用于任意列表,而不仅仅是连续范围。

[x**2 + x + 2 for x in range(1, 6)]

但是,在some circumstances中,使用map()可能更有利。

[x**2 + x + 2 for x in [4, 8, 14, 22, 32]]

我会在你的特定情况下使用列表理解,因为你似乎不需要为这样一个简单的表达式定义一个函数。

答案 3 :(得分:0)

您可以在fun(x)功能中执行此操作:

>>> x = range(1,6)
>>> 
>>> def fun(x):
    return [i**2+i+2 for i in x]

>>> fun(x)
[4, 8, 14, 22, 32]

答案 4 :(得分:0)

感谢您的帮助。以下是感兴趣的人的整个文件。它几乎没有接近完成,但我很快就需要完成这部分。我检查了我使用的答案,因为我已经走了一条死线,把它交给我的教授,但我肯定会看看你们提供的所有选项。

# This code is written for homework 4 in my Computational Physics.
# I will calculate the first 20 wavelengths (in nm = nanometers) for any series of
# hydrogen. Your code should allow the user to specify (via input) which 
# series of hydrogen are to be calculated (e.g., n = 1, Lyman series; n = 2,
# Balmer series; n = 3, Paschen series, etc.)

import math 

# Rydberg Constant for Hydrogen (m^-1)
Rh = 1096776000000

# Allows the user to specify which series of hydrogen that are going to 
# be using
print "What is your value for 'n'?"

# Had to make 'n' a float() instead of an int(), otherwise, later on when doing
# division, any non-integer values would be pushed to 0.
n = float(raw_input(">"))

# So m will define the first 20 energy levels for an electron in the hydrogen atom.
# I made it vary with respect to 'n' for obvious reasons.
m = range(int(n+1), int(n+21))  

# The wavelength() function is based off of the Rydberg constant for Hydrogen.
# The parts in parentheses are all taken from the formula, and the last part 
# ( * 10 ** 14) is that my output comes out as nanometers. To make the list 
# from 'm' run properly I had to use a for loop that defined the elements 
# of the list as 'x' and would run each one, individually, through the equation.
def wavelength(n,m):
    return [((1 / (Rh * ((1 / (n**2)) - (1 / (float(x)**2))))) * 10 ** 14)
    for x in m] 

# This will print out my elements. I used another for loop so as to format
# all 20 elements such that they would only have 3 digits past the decimal point.
for x in wavelength(n,m):
    print "%.3f" % x, 'nm'