【问题标题】:Iterating through a dictionary of lists and returning the character at the same index遍历列表字典并返回相同索引处的字符
【发布时间】:2019-10-04 04:06:55
【问题描述】:

从作为字符串传递的矩阵打印垂直列。

我创建了一个字典,并将矩阵的每一行分配为字典中的一个值,然后用括号括起来以创建一个列表字典。

想要遍历字典中的每个键并附加给定索引的值(例如,如果值为 'a b c',则返回 'a' 表示 1,' ' 表示 2...)但我只保留得到的是:

[['a b c '], ['a b c '], ['a b c ']]

或者当我摆弄它时对此的变化。尽管每个值显然是矩阵中的不同行,但它似乎永远不会超过第 1 行。

感谢任何帮助。

def column (str, index):
    output = []
    li = str.split("\n")
    row_dict = {
            1: [li[0]],
            2: [li[1]],
            3: [li[2]] 
            }
    for key in row_dict:
        output.append(row_dict[index])
    return output

str = "a b c \n d e f \n g h i"
column(str, 1)

【问题讨论】:

    标签: python


    【解决方案1】:

    首先,拆分"\n ",因为您似乎在每个换行符后都有一个空格。

    如果您使用列表推导式,则获取每行的第 n 个项目非常简单,例如[row[index] for row in s.split("\n ")].

    总共:

    >>> def column (s, index):
        return [row[index] for row in s.split("\n ")]
    
    >>> s = "a b c \n d e f \n g h i"
    >>> column(s, 1)
    [' ', ' ', ' ']
    

    或者,如果您希望它是 1-indexed(如问题中的示例)而不是 0-indexed:

    >>> def column (s, index):
        return [row[index-1] for row in s.split("\n ")]
    
    >>> s = "a b c \n d e f \n g h i"
    >>> column(s, 1)
    ['a', 'd', 'g']
    

    【讨论】:

    • 这解决了问题,感谢您提醒我注意列表理解。现在尝试使用:s = s.replace(“”,“”)从我的行中的字符之间去除空格,但是一旦包含该行,它就会再次返回单个字符......例如column(s, 1) = ['a']
    • @user3763074 然后确保将另一个拆分更改为没有空格:将return [row[index-1] for row in s.split("\n ")]更改为return [row[index-1] for row in s.split("\n")]
    【解决方案2】:

    据我所知,您的代码的唯一问题是您正在附加字典值(这是一行,而不是实际值,例如它在 key = 'index' 处获取行,而不是每个字典中位置“索引”处的值)输出,当你想从每一行分配一个特定的值时......这就是你应该做的:

    for key in row_dict:
        output.append(row_dict[key].split()[index])
        print (row_dict[key].split()[index])
    

    对于 index=1,这将打印:

    b
    e
    h
    

    这在一个语句中做了三件事:

    1. 从字典中获取存储在 key='key' 的字符串
    2. 将您的字符串拆分为单个字符(以便您可以更轻松地提取它们)
    3. 获取参数指定索引处的字符/单词。

    【讨论】:

      【解决方案3】:

      您可能忘记提及您正在迭代的key。你的函数应该是这样的:

      def column(str, index):
          output = []
          li = str.split("\n")
          row_dict = {
                  1: li[0].lstrip().split(' '),
                  2: li[1].strip().split(' '),
                  3: li[2].strip().split(' ')
          }
          for key in row_dict:
              output.append(row_dict[key][index])
          return output
      

      另外,请注意您在row_dict 的值中添加了额外的[]。最后,Python 中的可迭代对象从第 0 个索引开始,所以你可以像 column("a b c \n d e f \n g h i", 0) 这样调用你的函数。

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2014-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 2019-11-29
        相关资源
        最近更新 更多