python动态生成多个变量

最近刷leetcode遇到分行取字符串再重新拼接的题目,解题过程中使用了动态生成变量的相关办法。后来发现用字典更加简单。

动态生成如下:

1 for i in range(5):
2     locals()['L%s'%i] = 'haha'
3 locals()['L%s'%2] = 'xixi'
4 
5 print locals()['L%s'%1],locals()['L%s'%2],L2
6 
7 
8 output:
9 haha xixi xixi

其中运用了locals()来返回变量。

这个方法其实很一般,如果运用迭代来生成字典则非常简单。

附动态生成变量与字典的截图代码对比:

 1 #动态生成变量
 2 class Solution(object):
 3     def convert(self, s, numRows):
 4         if numRows == 1:
 5             return s
 6         names = locals()
 7         for i in range(1,numRows+1):
 8             names['l%s'%i] = ''
 9         n = 1
10         i = 0
11         while i < len(s):
12             while n < numRows:
13                 if i == len(s):
14                     break
15                 names['l%s'%n] += s[i]
16                 n +=1
17                 i +=1
18             while n > 1:
19                 if i == len(s):
20                     break
21                 names['l%s'%n] += s[i]
22                 n -= 1
23                 i += 1
24         out = ''
25         for i in range(1,numRows+1):
26             print names['l%s'%i]
27             out +=names['l%s'%i] 
28         print out
29         return out 
30 
31 
32 #使用字典
33 class Solution(object):
34     def convert(self, s, numRows):
35         if numRows == 1:
36             return s
37         ldict = {}
38         for i in range(1,numRows+1):
39             ldict[i] = ''
40         n = 1
41         i = 0
42         while i < len(s):
43             while n < numRows:
44                 if i == len(s):
45                     break
46                 ldict[n] += s[i]
47                 n +=1
48                 i +=1
49             while n > 1:
50                 if i == len(s):
51                     break
52                 ldict[n] += s[i]
53                 n -= 1
54                 i += 1
55         out = ''
56         for i in ldict.values():
57             out +=i 
58         return out 

字典显得简洁的多,更适合python。

 

posted @ 2018-08-23 16:48  slarker  阅读(5408)  评论(0编辑  收藏  举报