按顺序向列表添加元素?
我正在尝试使用从文件中读取的整数来初始化列表。每次读取一个整数时,我都会向列表中添加一个元素(由calculate()函数定义的元素),添加元素的索引就是我读取的整数。因此,如果我读到“5”,我想要一个元素存储在索引 5 处。文件中的整数在数字上是无序的,所以我不能简单地将 insert() 元素插入列表中,因为它可能会导致其他元素已经插入被插入以乱序推出。
items = []
for line in open(filepath, 'r'):
for c in line:
if c != '\n':
i = int(c)
items.insert(i, calculate(i)) #not working
如何按顺序添加它们?
I am trying to initialize a list using integers read from a file. Each time I read an integer I add an element to the list (the element defined by a calculate() function), and the index the element is added at is the integer I read. So if I read "5", I want an element stored at index 5. The integers in the file are out of order numerically, so I can't simply insert() elements into the list because it may cause other elements that have already been inserted to be pushed out of order.
items = []
for line in open(filepath, 'r'):
for c in line:
if c != '\n':
i = int(c)
items.insert(i, calculate(i)) #not working
How do I add them in order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 http://www.doughellmann.com/PyMOTW/bisect/ 找到了一个解决方案,其中类似的问题就解决了。
I found a solution at http://www.doughellmann.com/PyMOTW/bisect/ where similar problem is solved.