简体   繁体   中英

python for loop ; copy specific list item to another

List1 = ['a','b','c','d','e','f','g','h','i']
List2 = []

I want to copy item#3,6,9 from list1 to list2 using for loop. can anyone give me example code please.

You can just loop over the indices that you want using a list comprehension (remembering that python lists are zero indexed so item #3 is index 2, etc...):

List1 = ['a','b','c','d','e','f','g','h','i']
indices = [2,5,8]

List2 = [List1[i] for i in indices]

# ['c', 'f', 'i']

You can use enumerate() to loop through the items in a list and know their positions:

for position, item in enumerate(List1):
    if position in [2, 5, 8]:
        List2.append(item)

If you want to use for then

for i in range(2, 9, 3):
  list2.append(list1[i])

2 is index of 1st element to copy, 9 is one more than 8 (index of last element you want to copy), 3 indicates step length.

A more pythonic way would be to use slicing instead of for loop like so

list2.extend(list1[2:9:3])

Python lists always start from index 0, which is the 1st index, so if you wanted to get the 3rd, the 6th and the 9th item in the list, you should subtract 1 from their position in the list, then you would get their index and your will get index 2 as item 3, index 5 as item 6, index 8 as item 9.

List1 = ['a','b','c','d','e','f','g','h','i']
item_position = [3, 6, 9]
result = []
for i in item_position:
    result.append(List1[i-1])

print(result)

#['c', 'f', 'i']

This is not strictly a for-loop based method, but an alternative.

Slice-based indexing is a possibility when the elements are at equal intervals. A python slice is used to index into a list-type object. A slice has three items: start, stop, and step, and a slice is created as variable_name = slice(start, stop, step)

So we can do:

List1 = list('abcdefghi')                                                                                                                                                                                                                                                
indexing = slice(2, 9, 3)                                                                                                                                                                                                                                                
List2 = List1[indexing]   

                                                                                                                                                                                                                                           

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