gpt4 book ai didi

python - 重构代码/合并函数(例如嵌套 for 循环顺序)

转载 作者:行者123 更新时间:2023-11-28 23:01:38 25 4
gpt4 key购买 nike

只是一些背景知识:我正在制作一个程序,用户可以在其中输入骨架文本、两个数字(下限和上限)以及单词列表。输出是对骨架文本的一系列修改。

示例输入:

text = "Player # likes @." (replace # with inputted integers and @ with words in list)
lower = 1
upper = 3
list = "apples, bananas, oranges"

用户可以选择先迭代数字:

Player 1 likes apples.
Player 2 likes apples.
Player 3 likes apples.

或者先说词:

Player 1 likes apples.
Player 1 likes bananas.
Player 1 likes oranges.

我选择通过基于数字键(用户输入的整数)或单词键(来自输入列表中的单词)创建不同类型的字典来拆分这两种输出方法,然后迭代中的值字典。

这里有两种类型的字典创建:

def numkey(dict): # {1: ['Player 1 likes apples', 'Player 1 likes...' ] }

text, lower, upper, list = input_sort(dict)
d = {}

for num in range(lower,upper+1):
l = []
for i in list:
l.append(text.replace('#', str(num)).replace('@', i))
d[num] = l
return d

def wordkey(dict): # {'apples': ['Player 1 likes apples', 'Player 2 likes apples'..] }

text, lower, upper, list = input_sort(dict)
d = {}

for i in list:
l = []
for num in range(lower,upper+1):
l.append(text.replace('#', str(num)).replace('@', i))
d[i] = l
return d

我有两个单独的函数来创建不同类型的词典,这很好,但我发现两者之间有很多重复。有什么方法可以创建一个字典函数并向其传递不同的值,从而改变嵌套 for 循环的顺序以创建我正在寻找的特定 {key : value} 对?

我不确定这将如何完成。是否有任何与函数式编程或其他范例相关的内容可能对此有帮助?这个问题有点抽象,比任何问题都更注重风格/设计。

最佳答案

您不需要字典来生成输出。你可以使用类似的东西:

import itertools

numbers = range(lower, upper + 1)
words = "a, b, c".split(", ")

data = (numbers, words) if numbers_first else (words, numbers)
for n, w in itertools.product(*data):
if not numbers_first: n, w = w, n
print("Player %d likes %s." % (n, w))

要避免循环内的 if,您可以动态生成格式字符串,例如:

template = "Player # likes @."
subs = ("{n}", "{w}") if numbers_first else ("{w}", "{n}")
format = make_format(template, subs) # escape {}, replace # and @

# ...
for n, w in product(*data):
print(format.format(n=n, w=w))

关于python - 重构代码/合并函数(例如嵌套 for 循环顺序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10872049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com