[英]Python: looping through a list?
I have a list, example: 我有一个列表,例如:
mylist=["a", "b", "end"]
I want to append all values of mylist to a different list (new_list) and also add the string " letter" to each value of the new_list except the last one (value: end) 我想将mylist的所有值附加到不同的列表(new_list),并将字符串“letter”添加到new_list的每个值,除了最后一个(value:end)
So far I have a for loop that adds the string "letter" to all values: 到目前为止,我有一个for循环,它将字符串“letter”添加到所有值:
new_list = []
for x in my_list:
new_list.append(x + " letter")
which produces: 产生:
("a letter", "b letter", "end letter") (“一封信”,“b字母”,“结束信”)
I want: 我想要:
("a letter", "b letter", "end") (“一封信”,“b字母”,“结尾”)
This is best achieved with list comprehensions and slicing: 这可以通过列表推导和切片来实现:
>>> new_list = [s + ' letter' for s in mylist[:-1]] + mylist[-1:]
>>> new_list
['a letter', 'b letter', 'end']
We have to skip the last element, use list slices for this; 我们必须跳过最后一个元素,为此使用列表切片; using a list comprehension will also come in handy. 使用列表理解也会派上用场。 Try this: 尝试这个:
mylist = ['a', 'b', 'end']
new_list = [x + ' letter' for x in mylist[:-1]] + [mylist[-1]]
It works as expected: 它按预期工作:
new_list
=> ['a letter', 'b letter', 'end']
您可以为列表中除最后一个元素之外的每个元素添加" letter"
,然后只添加最后一个元素。
new_list = [x + " letter" for x in my_list[:-1]] + [my_list[-1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.