0

假设我有以下列表(我的脚本中的字符串变量):

dog = lab
cat = brown
fish = wet
dog = terrier
cat = angry
fish = cooked
dog = blah
cat = soon
fish = wegetthepattern

我需要一种方法来解析这个列表,并根据出现将它们设置为变量。所以最后它会设置如下变量:

dog1='lab'
dog2='terrier'
dog3='blah'
cat1='brown'
cat2='angry'

等等。我的列表中可能有 1 次表示 dog,或 200 次,我只需要一种方法来解析列表(当前是我正在调用的字符串变量)并设置这些变量,以便稍后在我的脚本中调用。

4

2 回答 2

3

对此通常的回答是:不要尝试去做

你可以尝试去实现它,但你会后悔的。将单词存储在 dict 中:

In [1]: s = '''dog = lab
   ...: cat = brown
   ...: fish = wet
   ...: dog = terrier
   ...: cat = angry
   ...: fish = cooked
   ...: dog = blah
   ...: cat = soon
   ...: fish = wegetthepattern'''

In [2]: from collections import defaultdict

In [3]: words = defaultdict(list)

In [4]: for pair in s.split('\n'):
   ...:    left, right = pair.split(' = ')
   ...:    words[left].append(right)
   ...:    

In [5]: words['dog']
Out[5]: ['lab', 'terrier', 'blah']
于 2013-04-16T19:05:57.567 回答
0
s = """dog = lab
cat = brown
fish = wet
dog = terrier
cat = angry
fish = cooked
dog = blah
cat = soon
fish = wegetthepattern"""

for i in s.split('\n'):
    exec(i.split()[0] + '= "' + i.split()[-1] + '"')

print(cat) # prints 'soon'

但是,您应该避免这种情况。

于 2013-04-16T19:05:00.970 回答