Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果列表索引超出范围,则替换字符_Python_List - Fatal编程技术网

Python 如果列表索引超出范围,则替换字符

Python 如果列表索引超出范围,则替换字符,python,list,Python,List,我有一份清单: ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3 1 ', '2 3 ', ''] 我想每三次打印一次这样的项目: ['5', '16', '12', '2', '1', ''] 但最后一项由于空字符串导致索引列表超出范围。 我想要的是用0替换所有空字符串 所以我想得到的结果是: ['5', '16', '12', '2', '1', '0'] 我不知道怎么做。以下是我想做的一件事: carac_list = ['2

我有一份清单:

['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
我想每三次打印一次这样的项目:

['5', '16', '12', '2', '1', '']
但最后一项由于空字符串导致索引列表超出范围。 我想要的是用0替换所有空字符串

所以我想得到的结果是:

['5', '16', '12', '2', '1', '0']
我不知道怎么做。以下是我想做的一件事:

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
actual = [item.split()[2] for item in carac_list]

print("Actual = " + str(actual))
您可以使用Python3.8中引入的

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
actual = [y[2] if len(y) == 3 else '0' for item in carac_list if (y := item.split())]
print(actual)
输出:

您可以使用Python3.8中引入的

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
actual = [y[2] if len(y) == 3 else '0' for item in carac_list if (y := item.split())]
print(actual)
输出:


与其他一些类似,但在列表理解中使用单个if和单个for,使用Python 3.8中的Walrus运算符+

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
out = [y[2] if len(y := x.split()) >= 3 else "0" for x in carac_list]

['5', '16', '12', '2', '1', '0', '0']

与其他一些类似,但在列表理解中使用单个if和单个for,使用Python 3.8中的Walrus运算符+

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
out = [y[2] if len(y := x.split()) >= 3 else "0" for x in carac_list]

['5', '16', '12', '2', '1', '0', '0']

为什么只有一个0而不是两个-从'23'和from?是的,它可能是两个0,最后一个空列表是我必须删除的东西,我的想法是,如果第三个字符是空的,列表将替换为一个0或两个。为什么只有一个0而不是两个-从'23'和from?是的,它可能是两个0,最后一个空列表是我必须删除的东西,我的想法是,如果第三个字符为空,列表将用0或2替换它。