Python 迭代列表中的字符串元素并将该字符串的一部分追加到空列表中

Python 迭代列表中的字符串元素并将该字符串的一部分追加到空列表中,python,string,list,Python,String,List,在下面的代码中,有一个包含交易名称、价格、颜色和日期的交易列表。我想在客户列表中加上名字“John”,“Jay”,在销售列表中加上价格1.21美元,在销售列表中加上2.12美元,在颜色列表中加上颜色“white”,“red”。 迭代列表只会给出“”中的元素(引号)。如何将名称、价格和颜色添加到这些空列表中 transaction = ['John:$1.21:white:09/15/17','Jay:$2.12:red:09/15/17','Leo:$3,5:blue:09/15/17'

在下面的代码中,有一个包含交易名称、价格、颜色和日期的交易列表。我想在客户列表中加上名字“John”,“Jay”,在销售列表中加上价格1.21美元,在销售列表中加上2.12美元,在颜色列表中加上颜色“white”,“red”。 迭代列表只会给出“”中的元素(引号)。如何将名称、价格和颜色添加到这些空列表中

    transaction = ['John:$1.21:white:09/15/17','Jay:$2.12:red:09/15/17','Leo:$3,5:blue:09/15/17']
    customers = [names_of_customer]
    sales = [price_of_goods]
    color = [color_of_goods]

您可以使用下面的代码段,它使用split方法来实现所需的输出

transaction = ['John:$1.21:white:09/15/17','Jay:$2.12:red:09/15/17','Leo:$3,5:blue:09/15/17']
customers=[]
sales=[]
color=[]
for tran in transaction:
    elems = tran.split(':')
    customers.append(elems[0])
    sales.append(elems[1]) 
    color.append(elems[2])

print customers
print sales
print color
str.split()
函数将字符串拆分为单独的元素。此后,可以遍历元素并将它们附加到相应的列表中。例如:

transactions = ['John:$1.21:white:09/15/17','Jay:$2.12:red:09/15/17','Leo:$3,5:blue:09/15/17']

customers = []
sales = []
colors = []
# dates = []

for transaction in transactions:
    item = transaction.split(":") # splits "transactions" on ':'
    customers.append(item[0])
    sales.append(item[1])
    color.append(item[2])
    # dates.append(item[3])

print(customers, sales, colors)
#python 2:
print customers, sales, colors

你能告诉我们你自己在哪里解决这个问题吗?您知道如何将特定分隔符上的字符串拆分为多个部分吗?您知道如何将新元素附加到另一个列表中吗?这些动作中的每一个都是你可能已经知道怎么做的基本动作,您不想让我们向您解释您已经知道的内容。只是我在如何将此“只说”名称专门附加到客户列表中或仅附加到颜色列表中的颜色上遇到了问题。当我附加整个内容时,会附加“John:$1.21:white:09/15/17”。