初学者在这里,寻找一些帮助与Python
现在,我定义了一个函数,返回列表列表:
def lenumerate(s):
a = (text.split())
b = ([len(x) for x in text.split()])
c = list(zip(a,b))
print
return c
text = "But then of course African swallows are nonmigratory"
l = lenumerate(text)
print(l)
然后打印出来:
[('But', 3), ('then', 4), ('of', 2), ('course', 6), ('African', 7), ('swallows', 8), ('are', 3), ('nonmigratory', 12)]
现在,我想编写函数的第二个版本,它将一个名为flip的布尔值(即True或False)作为第二个参数。翻转的默认值应为False
我可以颠倒顺序,使“非迁移”出现在开头,但这不是我想要的。我想保留顺序,只需一直翻到(3,“But”)
我很感激你能提供的任何帮助
Python functions can be called with a single list of arguments,而不是多个单独的参数
根据
flip
的状态,我们可以使用它来生成一组参数和一组相反的参数印刷品
注意事项
a
和b
Python的列表理解使得首先避免编写函数成为可能。上述函数可以写成:
这里有一个解决方案:
解释
split()
一次李>map
直接输入zip
。这意味着更多的工作是懒散地完成的,而不是建立不必要的列表李>if
/else
构造的惰性三元语句李>print
语句没有用处,可以删除李>相关问题 更多 >
编程相关推荐