-
阿波罗的战车
根据我对您的列表内容的理解,您可以使用如下内容:businesses = ["C1 count B1", "C2 count B2", "C1 count B3"]cities = ["C1","C3","C4"]output = [a for a in businesses if a.split()[0] in cities]print(output)假设空格分隔第一个列表中每个项目的组成部分,则会产生:['C1 count B1', 'C1 count B3']
-
www说
您错过了内部for循环的缩进for item1 in A: for item2 in B: if item1 == item2: print(item1)或者您可以使用setif 两个列表中的值都是单个单词来执行此操作list(set(A).intersection(set(B)))从你的问题来看,它是列表中单词的组合businesses = ["C1 count B1", "C2 count B2", "C1 count B3"]cities = ["C1","C3","C4"]for city in cities: for business in businesses: if city in business.split(): print(city, business)
-
慕标琳琳
for local_city in list_of_cities_in_our_district: for entry in list_of_city_county_business: if entry's city matches local_city: print the business name这是一些伪代码,应该可以完成您想要的操作...我将语义细节留给您,用于解析列表的布局等。
-
跃然一笑
鉴于所提供的数据文件中的数据格式不完美,以下代码可能会工作得更好。它还有一个额外的优点,即按照城市在 cars.txt 文件中出现的顺序按城市对结果进行分组。with open('Cities.txt', encoding='utf-8') as f: cities = f.read().split('\n')cities = [x.strip() for x in cities if x]with open('Businesses.txt', encoding='utf-8') as f: businesses = f.read().split('\n')businesses = [x for x in businesses if x]found = 0for c in cities: for b in businesses: if b.startswith(c): found += 1 print(b)print(f'Found {found} businesses')
-
慕田峪4524236
完整的解决方案,由于非结构化数据需要大量格式化。with open("Businesses.txt", mode='r') as f: listBusinesses = f.readlines()with open("Cities.txt", mode='r') as f: listCities = f.readlines()Cities = []for values in listCities: if len(values.split('\n')[0]) > 0: Cities.append(values.split('\n')[0])CityNames = []BusinessNames = []SerialNo = []for values in listBusinesses: if len(values.split('\n')[0]) > 0: vCityNames = values.split('\n')[0][:26].strip() CityNames.append(vCityNames) vSerialWithBusiness = values.split('\n')[0][26:].strip() if len(vSerialWithBusiness.split('\n')[0].split('.')) > 1: vSerialNo = (vSerialWithBusiness.split('\n')[0].split('.')[0].strip()) SerialNo.append(vSerialNo) vBusinessNames = (vSerialWithBusiness.split('\n')[0].split('.')[1].strip()) else: vBusinessNames = (vSerialWithBusiness.split('\n')[0].split('.')[0].strip()) SerialNo.append('Missing') BusinessNames.append(vBusinessNames)assert len(CityNames) == len(SerialNo) == len(BusinessNames)count = 0for x in range(len(Cities)): for y in range(len(CityNames)): if Cities[x] == CityNames[y]: count = count + 1 print(Cities[x].ljust(27,' ') ,SerialNo[y].ljust(7,' '), BusinessNames[y])# Total Businesses 3488, matching Cities 345