Skip to main content
 首页 » 编程设计

python之如何根据给定条件将字符串转换为二维列表

2024年12月31日20cyq1162

我将一个字符串作为输入。如果 @ 代表列而 # 代表行,我必须转换成二维列表或矩阵。

示例:1@-2@3#-3@2@4#-7@8@9 到 [[1,-2,3],[-3, 2,4],[-7,8,9]].

这是我的代码。我无法得到确切的结果。

a = input() 
b = a.split('#') 
c = [list(word) for word in b] 
print(c) 

但这给了我

[['1', '@', '-', '2', '@', '3'], 
 ['-', '3', '@', '2', '@', '4'], 
 ['-', '7', '@', '8', '@', '9']] 

('-' 属于下一个元素,它不是像 '-2' 这样的表达式)

请您参考如下方法:

你快到了。 c = [list(word) for word in b] 将单词中的每个字符转换为单独的元素。为防止出现这种情况,请先按照您喜欢的方式将元素分组到列表中:

c = [word.split('@') for word in b] 

如果你想让条目成为整数,你必须明确地这样做:

c = [[int(item) for item in word.split('@')] for word in b]