社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如果返回true,则使用相同的字典值重复python函数

dryer • 6 年前 • 1567 次点击  

任何人都可以帮助找到一种有效的方法,如何用列表值创建一个重复函数,在这里达到了true?

my_list = [value1, value2, value3]
 def my_func():
  score = 0
  for value in my_list:
   #do something
   if value > score
   repeat my_func with value2 as long as value > score

我相信我可以再次调用该列表,但它将开始迭代value1,我的目标是找到如何使函数在条件为真时迭代value2

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39192
 
1567 次点击  
文章 [ 2 ]  |  最新文章 6 年前
tobias_k
Reply   •   1 楼
tobias_k    6 年前

可以定义包装函数,应用给定函数 f 在某些情况下 cond 保留,然后将该函数应用于列表中的每个元素。

def repeat(func, cond, x):
    while cond(x):
        x = func(x)
    return x

>>> f = lambda x: x + 5
>>> [repeat(f, lambda x: x < 18, item) for item in [1, 3, 2]]
[21, 18, 22]

或者使用 functools.partial 要创建要应用的新函数,例如, map :

>>> import functools
>>> g = functools.partial(repeat, f, lambda x: x < 18)
>>> list(map(g, [1, 3, 2]))
[21, 18, 22]
Stonecutter
Reply   •   2 楼
Stonecutter    6 年前

我不确定我是否正确理解你的问题,但是如果你想在一个特定的值上达到真值,你可以通过一个“for”循环来实现:

my_list=[v1, v2, v3]
for i in my_list:
    if i <= crit_value:
        #Here you can call the function
        print('False')
    else:
        print('True')
        # Next line only when you want to quit the loop here
        break

对于本例,只要列表中的值较低或与临界值相同,就将停留在for循环中;如果高于临界值,则将退出循环并打印“true”。


编辑:

由于您的意思是值总是在变化,您可以这样做:

my_list=[v1, v2, v3]
# Now you use indices starting from zero until the number of elements in the list 
for i in range(len(my_list)):
    # I will set the number of maximum trys to 1000, this can be changed
    for j in range(1000):
        if my_list[i] <= crit_value:
            # Here you would need to reload my_list
            print('False')
        else:
            print('True')
            # To give you the actual value
            print(my_list[i])
            break