简体   繁体   English

遍历列表字典并返回相同索引处的字符

[英]Iterating through a dictionary of lists and returning the character at the same index

Working on printing a vertical column from a matrix passed as a string.致力于从作为字符串传递的矩阵中打印垂直列。

I've created a dictionary and assigned each row of the matrix as a value in the dict then bracketed to create a dictionary of lists.我创建了一个字典,并将矩阵的每一行分配为字典中的一个值,然后用括号括起来以创建一个列表字典。

Would like to iterate through each key in the dict and append the value of the given index (eg if value is 'ab c', return 'a' for 1, ' ' for 2...) but all I keep getting is:想遍历字典中的每个键和 append 给定索引的值(例如,如果值为 'ab c',则返回 'a' 表示 1,' ' 表示 2 ......)但我一直得到的是:

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

Or variations on this when I fiddle with it.或者当我摆弄它时对此的变化。 It never seems to get past row 1, although each value is clearly a different row in the matrix.尽管每个值显然是矩阵中的不同行,但它似乎永远不会超过第 1 行。

Appreciate any help.感谢任何帮助。

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)

As far as I can see, the only issue with your code is that you are appending the dictionary value (which is a row, and not the actual value, for example it is getting the row at key = 'index', rather than the value at location 'index' in each of the dictionaries) to output, when you want to assign a particular value from each row... this is what you should be doing:据我所见,您的代码的唯一问题是您正在附加字典值(这是一行,而不是实际值,例如它在 key = 'index' 处获取行,而不是每个字典中位置“索引”处的值)到 output,当你想从每一行分配一个特定值时......这就是你应该做的:

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

For index=1, this will print:对于 index=1,这将打印:

b
e
h

This does three things in one statement:这在一个语句中做了三件事:

  1. gets the string stored at key='key' from dictionary从字典中获取存储在 key='key' 的字符串
  2. splits your string into individual characters (so you can extract them more easily)将您的字符串拆分为单个字符(因此您可以更轻松地提取它们)
  3. Gets the character/word at the index specified by your parameters.获取参数指定的索引处的字符/单词。

First, split on "\n " because you seem to have a whitespace after each newline.首先,拆分"\n " ,因为您似乎在每个换行符后都有一个空格。

Getting the nth item of each row is pretty straightforward if you use list comprehensions, eg [row[index] for row in s.split("\n ")] .如果您使用列表推导,获取每行的第 n 个项目非常简单,例如[row[index] for row in s.split("\n ")]

Altogether:共:

>>> 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)
[' ', ' ', ' ']

Or, if you want it to be 1-indexed (like in the example in the question) instead of 0-indexed:或者,如果您希望它是 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']

You probably forgot to mention the key on which you were iterating.您可能忘记提及您正在迭代的key Your function should be something like:你的 function 应该是这样的:

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

Also, note that you were adding extra [] to the values of the row_dict .另外,请注意您在row_dict的值中添加了额外的[] Finally, iterable objects in Python start from a 0th index, so you would call your function like column("ab c \ndef \nghi", 0) .最后,Python 中的可迭代对象从第 0 个索引开始,因此您可以将 function 称为column("ab c \ndef \nghi", 0)

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM