假设我有以下列表(我的脚本中的字符串变量):
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'
等等。在我的列表中可能有一次说狗,或200,我只需要一种方法来解析列表(这是我正在调用的字符串变量)并设置这些变量,我可以稍后在我的脚本中调用它们。
答案 0 :(得分: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']
答案 1 :(得分: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'
但是你应该避免这种情况。