我对Python很陌生,只想提取这些客户地址的城市:
clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2,
Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]
有人可以帮忙吗?提前非常感谢您!
答案 0 :(得分:4)
您可以使用列表推导,并保留从第一个,
开始的每个字符串中的最后一个元素。
为此,请使用string.split
设置,
作为分隔符,它将在出现逗号时拆分每个字符串,将结果列表切成最后一个元素,然后使用string.strip
删除前导空格:
clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2,
Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]
[i.split(',')[-1].strip() for i in clients]
# ['Madrid', 'Sevilla', 'Madrid', 'Segovia']
有关上述方法的更多详细信息,建议您看看:
答案 1 :(得分:2)
如果clients
的元素始终为"name, address, city"
格式,则可以像这样split:
# List comprehension, splits each element of client on commas,
# then takes the final element (stripping any whitespace)
clients = [client.split(',')[-1].strip() for client in clients]
>>> print(clients)
['Madrid', 'Sevilla', 'Madrid', 'Segovia']
答案 2 :(得分:0)
不使用列表理解
clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2, Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]
list_of_cities =[]
for i in clients:
index_last_comma = 0
for j in range(len(i)-1,0,-1):
if i[j]==',':
index_last_comma = j
break
city = i[j+1:len(i)].strip()
list_of_cities.append(city)
print(list_of_cities)
# output ['Madrid', 'Sevilla', 'Madrid', 'Segovia']