【发布时间】:2023-03-12 11:59:01
【问题描述】:
代码正在运行并添加到列表中。但是,它向每个列表添加了三次而不是一次。我想将列表中的项目追加一次而不是三次。
我试图检查范围,它只有一个。但是,它仍然使用 append 方法添加到列表 3 次
newlist= [['id', 'name', 'lastContactedTime', 'email', 'phone_phones', 'home_phones', 'mobile_phones', 'work_phones', 'fax_phones', 'other_phones', 'address_1', 'address_2', 'address_3', 'city', 'state', 'postal_code', 'country', 'tags'], ['12-contacts', 'Courtney James', '', 'courtney@forlanchema.com', '+1 3455463849', '', '', '', '', '', '654 Rodney Franklin street', '', '', 'Birmingham', 'AL', '45678', 'US', ''], ['4-contacts', 'Joe Malcoun', '2019-08-13 14:41:12', 'ceo@nutshell.com', '', '', '', '', '', '', '212 South Fifth Ave', '', '', 'Ann Arbor', 'MI', '48103', 'US', ''], ['8-contacts', 'Rafael Acosta', '', 'racosta@forlanchema.com', '+1 338551534', '', '', '', '', '', '13 Jordan Avenue SW', '', '', 'Birmingham', 'AL', '45302', 'US', '']]
namelist = [] # new, empty list
for i in range(1, len(newlist)):
names = newlist[i][1].split() # this yields [first_name, last_name]
namelist.append([names[1], names[0]]) # [last_name, first_name]
companylist=[]
for i in range(1, len(newlist)):
p = re.compile(r'(.+)@(.+)\.(.+)')
test_str = newlist[i][3]
company= re.findall(p, test_str)
companyname= list(company[0][1])
companynom=''.join(companyname)
companylist.append(companynom) #yields company names
# strip non-numeric characters'
workphone = []
wrkstreetaddress = []
workcityaddress = []
wrkstate = []
wrkzip = []
for i in range(1, len(newlist)):
phone = re.sub(r'\D', '', newlist[i][4])
# remove leading 1 (area codes never start with 1)
phone = phone.lstrip('1')
workingphone= '{}.{}.{}'.format(phone[0:3], phone[3:6], phone[6:])
workphone.append(workingphone) #yields a list of workphone numbers
wrkstraddress= newlist[i][10]
wrkstreetaddress.append(wrkstraddress) #yields a list of work street addresses
wrkcityaddress= newlist[i][13] #yields a list of city addresses
workcityaddress.append(wrkcityaddress)
workstate= newlist[i][14] #yields a list of states
wrkstate.append(workstate)
workzip=newlist[i][15]
wrkzip.append(workzip) #yields a list of zip codes
我希望每个列表包含一个包含三个项目的列表:
如果我打印工作街地址列表,我会得到:
print(wrskstreetaddress)
['654 Rodney Franklin street', '212 South Fifth Ave', '13 Jordan Avenue SW']
instead of:
['654 Rodney Franklin street']
['654 Rodney Franklin street', '212 South Fifth Ave']
['654 Rodney Franklin street', '212 South Fifth Ave', '13 Jordan Avenue SW']
从 companylist 到 wrkzip 的所有其他列表都相同,我将项目添加三次而不是一次得到相同的结果
【问题讨论】:
-
您在说哪个列表,您的代码中有很多列表;)您确定最后一个循环的缩进(即在第二个循环内)吗?
-
您能更具体地谈谈您的问题吗?您提到“The List”有困难,但没有提及您指的是哪个列表。此外,此代码比您需要重现此问题的时间更长(我预测您可以在 3 行中完成)。请尝试删除不必要的代码并创建一个最小的完整示例:stackoverflow.com/help/minimal-reproducible-example
-
我投票结束这个问题,因为不清楚你在问什么,而且你没有回应试图获得更多信息的尝试。
-
我已添加列表
-
发布的缩进是否与您的代码中的缩进匹配?它实际上没有任何意义。
标签: python python-3.x list spyder