使用 split() 访问排序列表的元素



我创建了一个排序的字符串列表,使用

sorted_list=[[int(name.split("_")[-1]), name] for name in string_list]

输出看起来像

[[0, 'str_0'], [1, 'str_1'], [2, 'str_2'], [3, 'str_3']]

如何访问每对中的第二个元素?我想做

for the_str in sorted_list[1]:
    with open(the_str) as inf:

但是无效,我收到此错误ValueError: Cannot open console output buffer for reading

我该如何解决这个问题?

你可能想要这个:

for pair in sorted_list:
    with open(pair[1]) as inf:

这是你要找的吗:

for the_str in list(zip(*sorted_list))[1]:
    # code here

或只是:

for val in sorted_list:
    the_str = val[1]
    # code here

如果你遍历列表,你会得到一对接一对。您可以在 for 子句中拆分每个对的各个部分,并保留代码的其余部分:

for the_num, the_str in sorted_list:
    with open(the_str) as inf:

括号的嵌套表示有一个嵌套在 sorted_list[0] 中的列表列表,因此您需要先取消引用它。你想要sorted_list[0][i][1]。

最新更新