[英]Create a list with a value in it using only pure functions - python
Why this problem has no trivial solution is because I needs to be solved using only pure functions .为什么这个问题没有简单的解决方案是因为我只需要使用纯函数来解决。
Using only pure functions from Python's functional programming page ( https://docs.python.org/3/howto/functional.html# ), how can one create a list with a value in it?仅使用 Python 函数式编程页面( https://docs.python.org/3/howto/functional.html# )中的纯函数,如何创建一个包含值的列表? If we'd like to create a list with a value in it, we'd (in code) just do
如果我们想创建一个包含值的列表,我们会(在代码中)做
x = [1]
I do not consider []
to be to be a part of the functions we're looking at here, since it has no signature and is not callable like any other function.我不认为
[]
是我们在此处查看的函数的一部分,因为它没有签名并且不能像任何其他 function 一样可调用。
Using only functions to do this is not so trivial.仅使用函数来做到这一点并不是那么简单。 One thought I had was to create a new list using
list()
and then append values to it.我的一个想法是使用
list()
创建一个新列表,然后为其创建 append 值。 But list().append
is mutable and does not return a new, or the, list with the item in it.但是
list().append
是可变的,不会返回包含项目的新列表或列表。
What I really want to do is to turn ["a","b","c"]
into [["a"],["b"],["c"]]
, with above constraints.我真正想做的是将
["a","b","c"]
变成[["a"],["b"],["c"]]
,具有上述约束。
Other proposals has been made like creating my own (pure) function doing what I want:已经提出了其他建议,例如创建我自己的(纯)function 做我想做的事情:
def create_list(value) -> list:
return [value]
and then just do map(create_list, ["a","b","c"])
to get solution.然后只需执行
map(create_list, ["a","b","c"])
即可获得解决方案。 But this is a custom made function and is not from any of the python package functions (within https://docs.python.org/3/howto/functional.html , as mentioned) But this is a custom made function and is not from any of the python package functions (within https://docs.python.org/3/howto/functional.html , as mentioned)
Single element:单元素:
def to_list(elem):
return list(range(elem, elem+1)))
To convert [1,2,3]
into [[1], [2], [3]]
with list comprehesion (it can be easily changed to map
):将
[1,2,3]
转换为[[1], [2], [3]]
与列表理解(它可以很容易地更改为map
):
return [to_list(el) for el in input_list]
And without (ugly, but works ^^)并且没有(丑陋,但有效^^)
import itertools
def make_gen(elem):
yield elem
def to_list(elem):
return list(make_gen(elem))
def helper(elem, l):
return list(itertools.chain(to_list(to_list(elem)), l))
def convert(l):
if not l:
return []
return helper(l[0], convert(l[1:]))
print(convert([1, 2, 3]))
Using only pure functions from Python's functional programming page ( https://docs.python.org/3/howto/functional.html# ), how can one create a list with a value in it?
仅使用 Python 函数式编程页面( https://docs.python.org/3/howto/functional.html# )中的纯函数,如何创建一个包含值的列表? If we'd like to create a list with number 1 in it
如果我们想创建一个包含数字 1 的列表
You might exploit generator as generator are described therein as follows您可能会利用生成器作为生成器,其中描述如下
def justone():
yield 1
lst = list(justone())
print(lst)
output output
[1]
justone
is function (which might be checked using inspect.isfunction
) and is pure (as it does not alter anything outside) justone
是 function (可以使用inspect.isfunction
检查)并且是纯的(因为它不会改变任何外部)
lst=[1,2,3];
#this will print [[1],[2],[3]]
print(list(map(lambda x: [x],lst)));
In the documentation you link, there are references to Iterators and Generators, which are powerful constructs present in Python (and other languages).在您链接的文档中,有对迭代器和生成器的引用,它们是 Python(和其他语言)中存在的强大构造。 You can consider a function to build a list as follows:
您可以考虑使用 function 构建列表,如下所示:
def list_from_args(*args):
return [*args]
This is a (superfluous) wrapper around Iterator functionality.这是迭代器功能的(多余的)包装器。 You can leverage the Iterator pattern in Python to accomplish a lot, whether that be creating/consuming objects (eg lists, tuples, dictionaries), or for processing data (eg reading/writing to a file line-by-line, paginating an API or DB Query, etc.)
您可以利用 Python 中的迭代器模式来完成很多工作,无论是创建/使用对象(例如列表、元组、字典),还是处理数据(例如,逐行读取/写入文件,对 API 进行分页)或数据库查询等)
The code above does the following, for example:上面的代码执行以下操作,例如:
>>> example = list_from_args(1, 'a', 'ham', 'eggs', 44)
>>> example
[1, 'a', 'ham', 'eggs', 44]
The reason I labeled the above function as superfluous: Oftentimes, if you need to create a list on the fly, you can use list comprehensions .我将上述 function 标记为多余的原因:通常,如果您需要动态创建列表,可以使用列表推导。
To ensure non-mutability, you probably want to use tuples instead of lists (or be very disciplined with your lists).为了确保不可变性,您可能希望使用元组而不是列表(或者对您的列表非常自律)。
Using a list comprehension would be a valid functional approach:使用列表推导将是一种有效的功能方法:
A = [1,2,3]
B = [ [i] for i in A ] # [[1], [2], [3]]
or with tuples:或使用元组:
A = (1,2,3)
B = tuple( (i,) for i in A ) # ((1,), (2,), (3,))
If you must use functions, then map() is probably a good solution to this:如果你必须使用函数,那么 map() 可能是一个很好的解决方案:
A = [1,2,3]
B = list(map(lambda i:[i],A))
If even [i]
is proscribed (but why would it be), you can use aa function to make a list directly from its arguments:如果甚至
[i]
被禁止(但为什么会这样),您可以使用 aa function 直接从其 arguments 制作列表:
def makeList(*v): return list(*v)
A = makeList(1,2,3)
B = makeList(*map(makeList,A))
# combined
makeList(*map(makeList,makeList(1,2,3)))
BTW functional programming is not about "only using functions", it is more about non-mutability of results (and avoidance of side effects).顺便说一句,函数式编程不是关于“仅使用函数”,它更多的是关于结果的非可变性(以及避免副作用)。 You may want to question whoever is sending you on this wild goose chase.
你可能想问问是谁派你参加这场疯狂的追逐。
This does it using only functions from https://docs.python.org/3/library/functional.html这仅使用https://docs.python.org/3/library/functional.html中的函数来实现
import functools
import itertools
map(
list,
map(
functools.partial(
itertools.repeat,
times=1,
),
[1,2,3]
)
)
functools.partial
creates a new function of itertools.repeat
with "times" parameter set to 1. Each value in the list is then repeated once and turned into a new list using list
function. functools.partial
创建itertools.repeat
的新 function,其中“times”参数设置为 1。然后列表中的每个值重复一次,并使用list
function 转换为新列表。
>>> [[1], [2], [3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.