[英]Append length of string for each string in list
Input 输入
strlist = ['test', 'string']
Desired output: 期望的输出:
strlist = [('test', 4), ('string', 6)]
Attempt 1: 尝试1:
def add_len(strlist):
for i, c in enumerate(strlist):
strlist += str(len(strlist))
return strlist
Attempt 2: 尝试2:
def add_len(strlist):
for c in strlist:
c += " " + str(len(c))
return strlist
I realise I have the following issues: 我意识到我有以下问题:
Attempt 1: This results in an infinite loop, as the code keeps adding onto the list. 尝试1:这导致无限循环,因为代码不断添加到列表中。
Attempt 2: This does not add the value to the string, however, when I do, I get the infinite loop issue from #1. 尝试2:这不会将值添加到字符串中,但是,当我这样做时,我会从#1获得无限循环问题。
I believe I need to evaluate the number of elements in the list first and implement a while statement, but not quite sure how to do this. 我相信我需要首先评估列表中的元素数量并实现while语句,但不太确定如何执行此操作。
Use a list comprehension: 使用列表理解:
strlist = ['test', 'string']
def add_len(strlist):
return [(s, len(s)) for s in strlist]
You can use a list comprehension like this. 你可以使用这样的列表理解。
def add_len(strlist):
return [(s, len(s)) for s in strlist]
Or expanded, 或扩大,
def add_len(strlist):
new_list = []
for s in strlist:
new_list.append((s, len(s)))
return new_list
In the expanded form we can see the steps it's going through a bit more clearly. 在扩展形式中,我们可以更清楚地看到它所经历的步骤。
new_list
to put your strings and lengths into. new_list
以将字符串和长度放入。 strlist
. strlist
每个字符串。 new_list
. new_list
。 new_list
. new_list
。 Of course, both of these gives you your desired output: 当然,这两个都可以为您提供所需的输出:
[('test', 4), ('string', 6)]
Using map()
: 使用
map()
:
>>> strlist
['test', 'string']
>>> list(map(lambda x: (x, len(x)), strlist))
[('test', 4), ('string', 6)]
for i, c in enumerate(strlist)
The i
is the index of the element in the string list, and the c
the value of the element. i
是字符串列表中元素的索引, c
是元素的值。 And you keep on appending the results in place ( strlist
), so that the strlist
keeps growing. 并且您继续将结果附加到位(
strlist
),以便strlist
不断增长。
While the second attempt won't output your desired results. 虽然第二次尝试不会输出您想要的结果。 The result will be
strlist = ['test 4', 'string 6']
. 结果将是
strlist = ['test 4', 'string 6']
。 Every single element is not made up of tuple
. 每个元素都不是由
tuple
。
Meanwhile both the two attempts modify strlist
in place, which will bring in potential issues (affect other attributes/parameters that refer to strlist
). 同时,这两次尝试都会修改
strlist
,这将带来潜在的问题(影响参考strlist
其他属性/参数)。
A better solution for this is using list comprehension. 更好的解决方案是使用列表理解。
strlist = ['test', 'string']
new_strlist = [(s, len(s)) for s in strlist]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.