【问题标题】:Python-Value from list as a argument of other list列表中的 Python 值作为其他列表的参数
【发布时间】:2020-04-14 21:42:40
【问题描述】:

我对列表有疑问,因为我想从名为test_table 的列表中获取值,并将A_table 中的值作为参数。有没有办法得到正确的结果?当然列表不是空的,当我运行它时,我得到Process finished with exit code -1073740791 (0xC0000409)

            for x in range(len(A_table)):
                print(test_table[A_table[x]])

编辑: List_A 是这样生成的:(我认为问题是类型字符串而不是整数,但是 int 类型我的函数不起作用):

        A_letter = [find_all(sentence, 'A')]  
        A_string = ' '.join(map(str, A_letter[0]))
        data = A_string.split()  # split string into a list

        for temp in data:
            A_table.append(temp)

【问题讨论】:

    标签: python list data-structures


    【解决方案1】:

    这是你想要做的吗? 此代码查看test_list,如果找到该值,则通过调用list.index() 函数将其打印出来。

    list_a =[1,2,3,4]
    test_list = [3,5,8,9]
    
    for i in range(len(list_a)):
      if list_a[i] in test_list:
        print(test_list[test_list.index(list_a[i])])
    //output = 3
    

    【讨论】:

      【解决方案2】:

      首先,我不知道find_all 函数是在哪里定义的,但是如果它的行为类似于re.findall(您可能应该使用它),那么它已经返回一个列表,所以通过定义A_letter = [find_all(sentence, 'A')],你有一个匹配列表。

      考虑这个例子:

      >>> import re
      >>> sentence = 'A wonderful sample of A test string'
      >>> re.findall('A', sentence)
      ['A', 'A']
      

      继续前进,您的 A_table 有一个 liststr。所以没有直接的方法可以使用A_table 中的值来索引另一个列表。例如,即使test_table 具有值['A', 'B', 'C'],有效的索引值仍然是“0”、“1”和“2”,即我无法获得test_table['A'],因为列表只能由@ 索引987654334@.

      如果要获取列表中某个值(例如“A”)的索引,可以使用listindex 函数,它返回所提供值的第一个索引,或者引发一个ValueError 如果未找到该值。

      例如:

      >>> import re
      >>> 
      >>> test_table=['Q','F','R','A','B','X']
      >>> 
      >>> sentence = 'A wonderful sample of A test string'
      >>> A_table = re.findall('A', sentence)
      >>> 
      >>> for match in A_table:
      ...     # first check to ensure the match is in the test_table
      ...     if match in test_table:
      ...         # ok, I know it is here, so get the index
      ...         i = test_table.index(match)
      ...         v = test_table[i]
      ...         print(f'index [{i}] has value [{v}]')
      ... 
      index [3] has value [A]
      index [3] has value [A]
      
      

      编辑: Here is some more info.index 函数上,这是另一个指向your present error is related to memory corruption 的问题的链接。

      【讨论】:

        猜你喜欢
        • 2021-11-01
        • 2019-08-29
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        相关资源
        最近更新 更多