如何将此列表转换为几个字符串?

时间:2017-03-26 01:53:01

标签: python python-2.7

我有这个代码在矩阵中添加行的总和:

answer

但是[3, 5, 1]是一个看起来像answer的字符串。

如何使用循环(不包含.join)x转换为answer = [3, 5, 1]个变量?

示例answer1 = "3"它应该是:

answer2 = "5"

answer3 = "1"

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ // $("#div1").fadeIn(); $("#div2").fadeOut(3000); $("#div3").fadeIn(3000); }); }); </script> </head> <body> <p>Demonstrate fadeIn() with different parameters.</p> <button>Click to fade in boxes</button><br><br> <div id="div2" style="width:80px;height:80px;display:block;background-color:red;position:absolute"></div><br> <div id="div3" style="width:80px;height:80px;display:none;background-color:blue;position:absolute"></div> </body> </html>

2 个答案:

答案 0 :(得分:0)

这就是你想要的:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer1,answer2,answer3 = [str(sum(row)) for row in matrix]
print (answer1)
print (answer2)
print (answer3)

输出:

3
5
1

如果您想使用dict

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer = {index:str(sum(row)) for index,row in enumerate(matrix)}
print(answer)

输出:

{0: '3', 1: '5', 2: '1'}

或者,您可以使用list来存储答案:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer = [str(sum(row)) for row in matrix]
print(answer)

输出:

['3', '5', '1']

您可以参考使用answer[0]

回答0

答案 1 :(得分:-1)

如果您确实希望变量answer1 answer2和answer3等于答案,那么只需执行此操作

for i in answer:
    temp='answer'+str(i+1)+' = str(answer['+str(i)+'])'
    exec(temp)