下面的代码中有一个交易列表,其中包含交易的名称,价格,颜色和日期。我想在客户列表中附加名称说“ John”,“ Jay”,在销售列表中附加价格说$ 1.21,$ 2.12,在颜色列表中附加颜色说“白色”,“红色”。 迭代列表将只给出''(引号)内的元素。我如何将名称,价格,颜色专门添加到这些空列表中?:
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]
答案 0 :(得分:1)
您可以使用下面的代码段,该代码段使用 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
答案 1 :(得分:0)
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