Python 转换两元素列表的列表:[[word,length],[word,length],…]
我需要帮助编辑这个函数lenumerate(),它接受一个字符串 (如“s”)并返回包含每个单词和的两项列表的列表 它的长度:Python 转换两元素列表的列表:[[word,length],[word,length],…],python,string,python-3.x,list,string-length,Python,String,Python 3.x,List,String Length,我需要帮助编辑这个函数lenumerate(),它接受一个字符串 (如“s”)并返回包含每个单词和的两项列表的列表 它的长度:[['But',3],'then',4],'of',2],…['are',3],'nonmigratory',12] lenumerate(s)-将“s”转换为2元素列表:[[word, 长度],[字,长度],…] # Define the function first ... def lenumerate(s): l = [] # list for holding
[['But',3],'then',4],'of',2],…['are',3],'nonmigratory',12]
lenumerate(s)-将“s”转换为2元素列表:[[word,
长度],[字,长度],…]
# Define the function first ...
def lenumerate(s):
l = [] # list for holding your result
# Convert string s into a list of 2-element-lists
在此处输入您的代码
。。。然后调用lenumerate()对其进行测试
text = "But then of course African swallows are nonmigratory"
l = lenumerate(text)
print("version 1", l)
我想我需要列出并使用len()函数,但我不确定如何以最有效的方式使用这两个函数。以下是您想要的答案:
def lenumerate(s):
l = []
words = s.split(' ')
for word in words:
l.append([word,len(word)])
return l
我会在这里使用
列表理解
。因此:
def lenumerate (s): return [[word, len (word)] for word in s.split()]
让我解释一下这个漂亮的一行:
def
(或任何需要冒号的内容)。继续在冒号后面打字l
并在以后添加到它,而是通过将其括在括号中来当场创建和自定义它[word,len(word)]
,Python理解我将在for循环中定义word
,它:for
语句s.split()
(在空格处拆分)还有什么问题,就问吧 这里有一个简洁的方法:
text = "But then of course African swallows are nonmigratory"
def lenumerate(txt):
s = text.split(' ')
return list(zip(s, map(len, s)))
# [('But', 3), ('then', 4), ('of', 2), ('course', 6), ('African', 7),
# ('swallows', 8), ('are', 3), ('nonmigratory', 12)]
所以,这并不是要逐字逐句地发布家庭作业问题……首先,我只是在这一部分寻求帮助。第二,这个地方是用来解决编程问题的,这绝对属于这一类。快乐的编码。所以是关于修正你的代码,而不是实现你的想法/作业。请反复阅读,如果你有问题,请提供你的代码。@Brandi:如果你浏览这个网络,你会发现给学生的公开信的想法是帮助解决具体问题。就像我说的,我想我必须拆分列表并使用len函数,我只是不知道如何编码。但是,别担心,我正在删除我的帐户,因为这里的每个人都喜欢对其他人发牢骚。
def lenumerate (s): return [[word, len (word)] for word in s.split()]
text = "But then of course African swallows are nonmigratory"
def lenumerate(txt):
s = text.split(' ')
return list(zip(s, map(len, s)))
# [('But', 3), ('then', 4), ('of', 2), ('course', 6), ('African', 7),
# ('swallows', 8), ('are', 3), ('nonmigratory', 12)]