我的任务是获取下面的列表,并根据主列表的项中是否包含"-Flowers"或"-Shrub"来获得两个不同的列表。我使用列表解析和for循环来完成这两个任务。但是,我似乎无法使用removesufix()函数删除这些尾随部分并打印列表。
下面是我的代码
data = [
"Andromeda - Shrub",
"Bellflower - Flower",
"China Pink - Flower",
"Daffodil - Flower",
"Evening Primrose - Flower",
"French Marigold - Flower",
"Hydrangea - Shrub",
"Iris - Flower",
"Japanese Camellia - Shrub",
"Lavender - Shrub",
"Lilac - Shrub",
"Magnolia - Shrub",
"Peony - Shrub",
"Queen Anne's Lace - Flower",
"Red Hot Poker - Flower",
"Snapdragon - Flower",
"Sunflower - Flower",
"Tiger Lily - Flower",
"Witch Hazel - Shrub",
]
#List comprehension method
# flowers = [flowers for flowers in data if "Flower" in flowers]
# shrubs = [shrubs for shrubs in data if "Shrub" in shrubs]
#For loops method
flowers = []
shrubs = []
for strings in data:
if " - Flower" in strings:
trailing = strings
trailing.removesuffix(" - Flower")
flowers.append(trailing)
elif " - Shrub" in strings:
strings.removesuffix(" - Shrub")
shrubs.append(strings)
print(flowers)
print(f"\n")
print(shrubs)
这段代码可以工作,但我总是像删除没有发生一样获得结果:
['Bellflower - Flower', 'China Pink - Flower', 'Daffodil - Flower', 'Evening Primrose - Flower', 'French Marigold - Flower', 'Iris - Flower', "Queen Anne's Lace - Flower", 'Red Hot Poker - Flower', 'Snapdragon - Flower', 'Sunflower - Flower', 'Tiger Lily - Flower']
如何在列表解析和for循环方法中使用removesufix()来删除这些部分?
3条答案
按热度按时间ehxuflar1#
您需要指定
removesuffix
函数调用的输出:尽管在这种情况下,我还是建议您使用
endswith
作为if语句:g9icjywg2#
str.removesuffix()
内部检查给定字符串是否以某个后缀结束,因此如果不需要检查两次,您可以将原始字符串与从.removesuffix()
返回的字符串进行比较,如果不相同,则意味着字符串中存在后缀:你可以用海象把它变短:
vlju58qv3#
变更
到