Skip to main content
 首页 » 编程设计

python之如何分隔列表python 2.7的每一行

2024年10月01日9JustinYoung

我使用的是 python 2.7,我有一个包含产品价格和该产品链接的列表。每个价格和链接都被视为列表中的一项。问题是价格应该只在末尾,列表中的某些项目在开头和结尾都有价格。如果价格在开头,则项目以“$”开头,后跟价格和“\n”。当我使用 '\n'.join(list) 打印列表时,它将开头的价格(我想删除)和项目本身分开在单独的行上,但我不知道如何删除以 '$' 开头的行而不删除整个项目。现在我正在使用这段代码:

myList = map(' '.join,zip(list1, list2)) 
das = '\n'.join(x3x)  
print das 
#prints something like this: 
$30                            #<--this line is part of the item in the  
iPhone 4 $30. eBay.com/iphone4 #list but I want to remove it because  
                               #it is repetitive and messes up what i'm 
                               #trying to do. 

我通常使用的是:List = [v for v in myList if not v.startswith('$')] 但如果它以 '$' 开头,这将删除整个项目,不仅仅是其中带有“$30”的那一行。

现在是列表的示例:

['$34\n'iphone 4 $34 forsale.com/iphone4s, new car $20000 forsale.com/newcar] 
#lets just say it is 2 items in the list, the first item has the price before 
# and after the product, but the second item doesn't. I want to remove the '$34'  
# from the first item, but dont know how without deleting the entire 1st item. 

所以第一项是价格,产品,价格,然后是链接。有时价格会在产品之前,这会弄乱我的代码,所以我想删除恰好在我的项目开头的每个价格而不删除整个内容。

请您参考如下方法:

检查列表项是否以$开头,如果是,拆分列表项并删除第一部分。

lista = ['$34 iphone 4 $34 forsale.com/iphone4s', 'new car $20000 forsale.com/newcar'] 
 
for i in range(len(lista)): 
 
    if lista[i].startswith("$"): 
 
        lista[i] = " ".join(lista[i].split(" ")[1:]) 
 
print lista   

输出:

['iphone 4 $34 forsale.com/iphone4s', 'new car $20000 forsale.com/newcar']