gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:47 25 4
gpt4 key购买 nike

我使用的是 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']

关于python - 如何分隔列表python 2.7的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43649294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com