簡體   English   中英

替換列表中的字符串 integer,python

[英]replacing string integer in list, python

我想用 integer 替換字符串所以我首先嘗試了這個

timeupseats=[0,480,480,0]
for n in range(0,4): 
   if timeupseats[n]==0:
       timeupseats[n]='CLOSED'
for n in range(0,4): 
   if timeupseats[n]=='CLOSED':
       timeupseats[n]==0

因為第一個代碼不起作用,所以我第二次嘗試了這個代碼,它起作用了

timeupseats=[0,480,480,0]
for n in range(0,4): #print closed when there is no ticket left
    if timeupseats[n]==0:
        timeupseats[n]='CLOSED'
timeupseats = [0 if i=='CLOSED' else i for i in timeupseats]

第一個代碼和第二個代碼有什么區別? 為什么只有第二個代碼有效?

在您的第一組代碼中,最后一行出現此錯誤: timeupseats[n]==0

您想將其設置為0 (=)而不是檢查相等性(==)

有很多方法可以做到這一點。 在我看來,最強大的方法是首先定義要替換的值,然后使用“map”將其應用於列表的每個元素:

# make some data
ls = list(range(10))
# define values to replace
mapping = {0: 'CLOSED'}
# do replacement 
ls = list(map(lambda x: mapping.get(x, x), ls))
print(ls)

還有更明確但更難維護的方式:

ls = list(range(10))
for i, x in enumerate(ls):
    if x == 0:
        ls[i] = 'CLOSED'

print(ls)   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM