为了更清楚地理解我的问题的本质,我会说我想做什么。我有两个文件,第一个存储产品的商品和价格,第二个存储产品的必要货号,数量比第一个少。我需要将第一个文件中的价格分配给第二个文件的文章。为此,我想使用二进制搜索
下面是一个二分查找的例子:
nums = [5,7,6,9,8,4,2,3,1]
nums.sort()
print(nums)
search = 7
print('Мы хотим найти: ', search)
lowest = 0
highest = len(nums) - 1
index = None
while(lowest <= highest) and (index is None):
mid = (lowest+highest) // 2
if nums[mid] == search:
index = mid
else:
if search < nums[mid]:
highest = mid - 1
else:
lowest = mid + 1
print('Искомый элемент: ', nums[index])
这是我的脚本:
import csv
import os
import xlrd
file_art = 'Артикулы всех товаров Aurora.csv'
file_quan = '2.xls'
def get_comparison(file_art, file_quan):
product_all = []
quantity = []
price = []
with open(file_art, "r") as file_obj:
reader = csv.reader(file_obj)
for row in reader:
check = "".join(row)
if check == 'Articul':
pass
else:
product_all.append(int(check))
product_all.sort()
print(product_all)
excel_data = xlrd.open_workbook('./' + file_quan)
sheet = excel_data.sheet_by_index(0)
row_number = sheet.nrows
for row in range(1, row_number):
quantity.append(int((str(sheet.row(row)[1]).replace('.0','').replace('number:',''))))
price.append(str(sheet.row(row)[8]).replace('number:',''))
quantity.sort()
print(price)
get_comparison(file_art, file_quan)
列表元素的索引: price, quantity, 相互匹配(即列表的文章quantity对应列表中的价格price),但是当我对列表进行排序时quantity,我失去了价格和文章元素的索引的对应关系列表。是否可以以某种方式将索引分配quantity给 price?我希望我解释清楚,如果不清楚,请提问))))
对于每项任务,有必要寻找最合适的工具来解决它。您的任务是使用 Pandas 的 DataFrame 的经典(直接教育)任务。
创建两个数据框而不是(可能来自)您的表。然后对它们执行任何操作 - 在你的情况下 - 按文章连接两个框架。在一行中,您会得到问题的答案,以及您能想到的许多其他问题的答案。排序、计算各种金额等统计信息 - 在一个语句中完成,有时甚至更容易。