简体   繁体   中英

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)

So far I have a for loop that adds the string "letter" to all values:

new_list = []

for x in my_list:
   new_list.append(x + " letter")

which produces:

("a letter", "b letter", "end letter")

I want:

("a letter", "b letter", "end")

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM