【问题标题】:Python. Trying to get index[0] == index[1]Python。试图获取 index[0] == index[1]
【发布时间】:2017-10-05 08:10:53
【问题描述】:

运行此代码时出现索引超出范围错误。如果 tmp > 3 并且如果 tmp[2] == tmp[3] 则有效。满足条件时,我试图将 index[0] 中的数字写入文件。又名 tmp[0] == tmp[1]。为什么无论我尝试了什么,我都无法调用 tmp[0]。

i = 0
tmp = []
while(i < len(sequence)):
    tmp = sequence[i].replace("(","").replace(")","").split(",")
    if(len(tmp) > 1):
        if(tmp[0] == tmp[1]):
            print tmp[0]
            with open(output_file1, 'a') as output:
                output.write(str(tmp[0])  + '\n')
i = i+1
return True

python app.py
Traceback (most recent call last):
File "app.py", line 71, in <module>
generate(6, out_path2,out_path1, out_path)
File "app.py", line 45, in generate
random6th = random.choice(sequence2).replace("[", "").replace("]","").replac
e("'","").replace(" ","")
File "C:\Python27\lib\random.py", line 275, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is emp
ty
IndexError: list index out of range

i = 0
tmp = []
while(i < len(sequence)):
    tmp.append(sequence[i].replace("(","").replace(")","").split(","))
    if(len(tmp) > 0):
        if(tmp[0] == tmp[1]):
            print tmp[0]
            with open(output_file1, 'a') as output:
                output.write(str(tmp[0])  + '\n')
i = i+1
return True

Traceback (most recent call last):
File "app.py", line 69, in <module>
generate_2(seq_path, out_path1, out_path2);
File "app.py", line 20, in generate_2
if(tmp[0] == tmp[1]):
IndexError: list index out of range

使用第二个代码,我在 if(tmp[0] == tmp[1] 处遇到另一个回溯错误 使用 PRINT tmp[0],从不运行上述错误的第二个代码回溯。

一个序列看起来像这样

(8, 16, 5, 5, 65, 27)
(7, 15, 4, 4, 64, 26)
(21, 17, 12)
(22, 22, 11, 11, 59, 24)
(21, 21, 10, 9, 58, 23)

我正在尝试匹配 21 和 21 tmp[0] == tmp[1],然后写入文件 21。

【问题讨论】:

  • 你能分享一下确切的回溯吗?
  • 你也可以在分配后给我们一个print(tmp)的输出吗?
  • sequence[i].replace("(","").replace(")","").split(",") 看起来像穷人的ast.literal_eval
  • 什么是index[0]? (您也不要在循环中的任何地方更改i。)
  • index[0] 是 6 位数字列表中的一个数字,例如 1 2 3 4 5 6,其中 1 是 index[0]

标签: python python-2.7 indexing


【解决方案1】:

您在while 循环之前设置tmp = [],但每次进入循环时都重新分配它。您的代码应该是:

i = 0
tmp = []
while(i < len(sequence)):
    tmp.append(sequence[i].replace("(","").replace(")","").split(","))
    if(len(tmp) > 1):
        if(tmp[0] == tmp[1]):
            print tmp[0]
            with open(output_file1, 'a') as output:
                output.write(str(tmp[0])  + '\n')

这可能会解决您的问题。

【讨论】:

  • 将列表附加到列表可能不是 OP 想要的
  • 由于sequence[i] 看起来像列表中的一个项目,它会附加一个序列项目(在这个上下文中看起来是一个字符串)。
【解决方案2】:

好的,看起来数据在一个字符串列表中(假设您正在调用字符串方法),所以在这个假设下,这应该可以工作:

# sequences = \
# """(8, 16, 5, 5, 65, 27)
# (7, 15, 4, 4, 64, 26)
# (21, 17, 12)
# (22, 22, 11, 11, 59, 24)
# (21, 21, 10, 9, 58, 23)"""
# sequences = sequences.split('\n')

# Alternatively, if the data is within a textfile called sequence.txt
with open(os.path.join(home_dir, 'sequence.txt'), 'r') as infile:
    sequences = infile.read().splitlines(keepends=False)

output_file1 = 'good_sequences.txt'

# assuming you were using mode='a' only because open was called each iteration, otherwise change to 'a'
with open(output_file1, 'w') as outfile:  
    for sequence in sequences:
        seq_data = sequence.replace('(', '').replace(')', '').replace(' ', '').split(',')
        if seq_data and len(seq_data) > 2:
            if seq_data[0] == seq_data[1]:
                print(seq_data[0])
                # didn't see a need to cast as str
                outfile.write(seq_data[0] + '\n')

输出将是:

22
21

【讨论】:

  • 该代码可以使用它,但是,sequence = os.path.join(home_dir, 'sequence.txt') 我正在使用,它不会打印 seq_data[0]
  • 最后一个不输出任何东西到文件或打印 seq_data[0], no print no output tho
  • 尝试将 sequence.txt 与您的代码放在同一个文件夹中,然后使用with open('sequence.txt', 'r') as infile 如果这样可行,那么您遇到的问题与我们在这里回答的问题不同。如果它不起作用,那么我不明白您的数据文件是如何组织的。我正在用这个 sequence.txt 测试这段代码:dropbox.com/s/t0fy10t7mmb8mdt/sequence.txt?dl=0 和你的一样吗?
【解决方案3】:

我解决这个问题的最简单方法是更改​​ int(tmp[0]) == int(tmp[1]) 现在这个技巧效果很好。

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多