python列表get值验证位置超出范围

2024-10-02 12:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手。你知道吗

我有一个Python列表。然后我想打印列表中每个位置的数据,但如果此位置为空,请将其替换为空白:

["abcd", "12", "x"] => "a1xb2 c  d  "

我想做一个循环来验证每个位置的数据。但是,当列表中的某个位置为空时,我无法进行验证,因为我获得了索引超出范围的错误,那么就不可能进行验证。你知道吗

如何在Python中获取列表的值,该列表的范围可能为空,以便进行验证。你知道吗


Tags: 数据列表错误空白abcd新手超出范围a1xb2
2条回答

izip_longest来自itertools是你的朋友。它使用最长的iterable(此处为字符串),并用可设置为所需空格的填充值替换缺少的字符:

from itertools import izip_longest

def f(strings):
    return ''.join(
        map(lambda x: ''.join(x), izip_longest(*strings, fillvalue=' '))
    )


a = ["abcd", "12", "x"]

print(repr(f(a)))

结果:

'a1xb2 c  d  '

chain代替map和第二个join的变体。你知道吗

def f(strings):
    return ''.join(
        chain(*izip_longest(*strings, fillvalue=' '))
    )

应用于数组a的最后一个方法的中间步骤:

from pprint import pprint

a1 = izip_longest(*a, fillvalue=' ')
print('# After izip_longest:')
pprint(list(a1))

print('# After chain:')
a1 = izip_longest(*a, fillvalue=' ')
a2 = chain(*a1)
pprint(list(a2))

a1 = izip_longest(*a, fillvalue=' ')
a2 = chain(*a1)
a3 = ''.join(a2)
print('# Result:')
pprint(a3)

结果:

# After izip_longest:
[('a', '1', 'x'), ('b', '2', ' '), ('c', ' ', ' '), ('d', ' ', ' ')]
# After chain:
['a', '1', 'x', 'b', '2', ' ', 'c', ' ', ' ', 'd', ' ', ' ']
# Result:
'a1xb2 c  d  '

由于您对Python还不熟悉,根据Zen of Python简单优于复杂,这里有一个只使用最简单Python结构的解决方案:

from __future__ import print_function

str_ = ["abcd", "12", "x"]

max_len = max(len(i) for i in str_)
out = ""

for i in range(max_len):
    for j in str_:
        try:
            out += j[i]
        except IndexError:
            out += " "

print(out)

作为SO的新手,我建议您阅读https://stackoverflow.com/help/on-topichttps://stackoverflow.com/questions/how-to-askhttps://stackoverflow.com/help/mcve。你知道吗

相关问题 更多 >

    热门问题