Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Python 3.x_List_Split - Fatal编程技术网

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

Python 如何根据给定条件将字符串转换为二维列表,python,python-3.x,list,split,Python,Python 3.x,List,Split,我接受一个字符串作为输入。如果@表示列,而#表示行,则必须将其转换为二维列表或矩阵 示例: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'

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

示例:
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'
那样的表达式)

这里有一种方法,使用
拆分
分别对
@
执行行拆分和列拆分,并将
单元格映射到
int

s = "1@-2@3#-3@2@4#-7@8@9"

print([list(map(int, x.split("@"))) for x in s.split("#")])
输出:

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

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

c = [word.split('@') for word in b]
如果要使条目成为整数,则必须明确执行以下操作:

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

理解中的@分裂