[英]how to append a list in python with for loop
我想附加my_list
list2 = ['1','2','3','4','5']
my_list = []
for i in list2:
my_list.append(i)
print(my_list)
這會將list2放入my_list。
結果是
['1', '2', '3', '4', '5']
但我只想要值'2'和'5')
所以像這樣:
[ '2', '5']
試過
for i in list2:
my_list.append(i[1:4])
任何想法?
僅將一種條件與list comprehension
結合使用:
my_list = [item for item in list2 if item == '2' or item == '5']
這取決於如何確定應將list2的哪些元素添加到my_list中,而您沒有提到:
現在,您可以按照@ MihaiAlexandru-Ionut的建議進行操作。
要么:
list2 = ['1','2','3','4','5']
my_list = []
my_list.append(list2[1])
my_list.append(list2[4])
print(my_list)
# or
my_list = []
my_list = [list2[1], list2[4], ]
print(my_list)
這是一個簡短的方法。 但是請注意,如果列表中有重復的元素,它將中斷。
list2 = ['1','2','3','4','5']
my_list = []
want = ['2', '5']
my_list = [list2[list2.index(i)] for i in list2 for item in want if i == item] # will fail if elements are not unique.
最后一行與此等效
my_list = [item for i in list2 for item in want if i == item] # much better than using index method.
這是擴展形式。
list2 = ['1','2','3','4','5']
my_list = []
want = ['2', '5']
for i in list2:
for item in want:
if i == item:
my_list.append(list2[list2.index(i)])
#my_list.append(item)
print(my_list)
可能是這樣
list2 = ['1','2','3','4','5']
target_idexes = [2, 5]
my_list = []
for i in list2:
my_list.append(i) if int(i) in target_idexes else 0
print(my_list) # ['2', '5']
或如果在list2中不僅只有數字:
list2 = ['1','2','3','4','5']
target_idexes = [2, 5]
my_list = []
for i in list2:
my_list.append(i) if list2.index(i) in target_idexes else 0
print(my_list) # ['3'] because indexing start from 0 and 5 is out of range
最簡單,最快的方法是對循環中要搜索的特定值使用條件語句。
if i == 2 or i == 5:
new_list.append(i)
這種方法的缺點是,如果需要擴展要檢索的值的范圍, if i == 1 or i == 5 ... or i == N:
,需要寫最長的條件,即因為很難維護代碼,所以不僅看到不好,而且編程習慣也很差。
更好的方法是使用一個列表,其中包含要檢索的值,並在將實際元素添加到新列表之前檢查該元素是否為該列表。
list2 = ['1','2','3','4','5']
wanted = ['2','5'] #what I search
my_list = []
for value in list2:
if value in wanted: #when value is what a I want, append it
my_list.append(value)
但是,如果要按元素的位置添加元素,而不是查找每個出現的特定值,則可以使用整數列表並對其進行循環以添加所需的元素。
positions = [1,4] #indicates the positions from which I want to retrieve elements
new_list = [list[p] for p in positions] #using list comprehension for brevity
我要添加的最后一件事是在python中無法執行
my_list.append(i[0,4])
因為python在查看[0,4]時,將像傳遞元組一樣解釋它( 由於逗號 ),並且會引發以下錯誤TypeError: list indices must be integers or slices, not tuple
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.