fruits=["apple","banana","melon"]
for fruit in fruits:
print fruit #print1
print len(fruit) #print2
我知道此脚本的输出如下所示
apple
5
banana
6
melon
5
但是我想像这样运行该脚本
#print1>#print1>#print1>#print2>#print2>#print2
所以输出将类似于
apple
banana
melon
5
6
5
有什么好的方法吗? (要点是我想一次用于功能) (不好意思,不好意思)
答案 0 :(得分:1)
您可以创建要调用的函数列表,然后首先遍历它们,然后遍历fruits
:
fruits = ["apple", "banana", "melon"]
for func in [lambda x: x, len]:
for fruit in fruits:
print(func(fruit))
输出
apple
banana
melon
5
6
5
答案 1 :(得分:1)
最简单的方法是将循环迭代两次:
fruits = ["apple", "banana", "melon"]
for _ in range(2):
for fruit in fruits:
print fruit
给出:
apple
banana
melon
apple
banana
melon
这避免了复制列表对象,避免了重复代码,并且易于扩展。
编辑:分别遍历两个不同的函数,您可以遍历列表两次:
fruits = ["apple", "banana", "melon"]
for fruit in fruits:
print fruit
for fruit in fruits:
print len(fruit)
对于更复杂的情况,您还可以列出函数并进行迭代:
def print_name(item):
print(string)
def print_name_length(item):
print(len(item))
fruits = ["apple", "banana", "melon"]
for func in (print_name, print_name_length):
for fruit in fruits:
func(fruit)
答案 2 :(得分:0)
您似乎可以在同一列表中循环两次以实现所需的日志记录:
for i in range(2):
for fruit in fruits:
print(fruit)
答案 3 :(得分:0)
您可以使用生成器表达式:
<Task commandLine="1.exe" executionContext="elevated" taskType="background"
<Environment>
<Variable name="Deployment">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/ConfigurationSettings/ConfigurationSetting[@name='DeploymentName']/@value" />
</Variable>
<Variable name="Service">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/ConfigurationSettings/ConfigurationSetting[@name='ServiceName']/@value" />
</Variable>
<Variable name="Stamp">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/ConfigurationSettings/ConfigurationSetting[@name='StampName']/@value" />
</Variable>
</Environment>
</Task>
输出:
fruits=["apple","banana","melon"]
def getfruits(fruits):
for f in fruits:
print(f)
yield str(len(f)) + '\n'
print(*list(getfruits(fruits)))
答案 4 :(得分:0)
fruits=["apple","banana","melon"]
for lists in (fruits, (len(fruit) for fruit in fruits)):
for each_list in lists:
print(each_list)
我循环遍历两个列表。水果和包含水果长度的列表。
然后我打印出每个列表。
这可能会提高内存效率,但这对我来说最有意义。我是为了提高可读性。
答案 5 :(得分:-1)
您可以只运行两次相同的循环。
fruits = ["apple","banana","melon"]
for f in fruits:
print f
for f in fruits:
print f
将为您带来结果。它可能很难看,但可以完成工作。
答案 6 :(得分:-1)
无法在一个循环中执行此操作。有什么原因不能解决这个问题?
for fruit in fruits:
print fruit #print1
for fruit in fruits:
print fruit #print2