我正在尝试编写一个数值聚类工具。基本上,我有一个列表(这里称为'product'),它应该从升序列表转换为指示数据集中数字之间的链接的列表。读取数据集,删除回车符和连字符可以正常工作,但基于数据集操作列表会给我带来问题。
# opening file and returning raw data
file = input('Data file: ')
with open(file) as t:
nums = t.readlines()
t.close()
print(f'Raw data: {nums}')
# counting pairs in raw data
count = 0
for i in nums:
count += 1
print(f'Count of number pairs: {count}')
# removing carriage returns and hyphens
one = []
for i in nums:
one.append(i.rsplit())
new = []
for i in one:
for a in i:
new.append(a.split('-'))
print(f'Data sets: {new}')
# finding the range of the final list
my_list = []
for i in new:
for e in i:
my_list.append(int(e))
ran = max(my_list) + 1
print(f'Range of final list: {ran}')
# setting up the product list
rcount = count-1
product = list(range(ran))
print(f'Unchanged product: {product}')
for i in product:
for e in range(rcount):
if product[int(new[e][0])] < product[int(new[e][1])]:
product[int(new[e][1])] = product[int(new[e][0])]
else:
product[int(new[e][0])] = product[int(new[e][1])]
print(f'Resulting product: {product}') 我希望结果是0,1,1,1,1,5,5,7,7,9,1,5,5,但在使用不同的数据集时,我遇到了“列表索引超出范围”。
用于给出上述所需产品的数据集如下:'1-2\n','2-3\n','3-4\n','5-6\n','7-8\n','2-10\n','11-12\n','5-12\n','\n‘
然而,我面临的最大问题是使用其他数据集。如果没有额外的回车,我将会出现列表索引超出范围的错误。
发布于 2019-09-12 00:51:08
我不太明白你到底想做什么。“指示链接”是什么意思,最终输出如何做到这一点?另外,你能给出一个数据集的例子,它实际上失败了吗?并提供您得到的实际异常?
无论如何,您的代码过于复杂,稍微清理一下也可以解决索引问题。使用上面示例中的nums:
# Drop empty elements, split on hyphen, and convert to integers
pairs = [list(map(int, item.split('-'))) for item in nums if item.strip()]
# You don't need a for loop to count a list
count = len(pairs)
# You can get the maximum element with a nested generator expression
largest = max(item for p in pairs for item in p)此外,在最后一个循环中,您将迭代product,同时就地修改它,这往往不是一个好主意。如果我对你想要实现的目标有更多的了解,我也许能提出一个更好的方法。
https://stackoverflow.com/questions/57893207
复制相似问题