while 루프를 통해 어떻게 변수를 동적으로 만들 수 있습니까? [복제]
이 질문에는 이미 답변이 있습니다.
- 변수 수의 변수를 작성하는 방법 답변 13 개
파이썬에서 while 루프를 통해 변수를 동적으로 만들고 싶습니다. 누구든지 이것을 할 수있는 창조적 인 수단이 있습니까?
변수 이름을 엉망으로 만들어야 할 필요가 없다면 사전을 사용하면 키 이름을 동적으로 만들고 각 값을 연결할 수 있습니다.
a = {}
k = 0
while k < 10:
<dynamically create key>
key = ...
<calculate value>
value = ...
a[key] = value
k += 1
새로운 '컬렉션'모듈에는 적용 가능한 흥미로운 데이터 구조도 있습니다.
http://docs.python.org/dev/library/collections.html
globals ()를 사용하면 가능합니다.
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
하나의 결과 :
'alphabet'
'random'
('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')
어떤 "변수"의 이름과 어떤 값을 만들지 설명하지 않기 때문에 임의를 사용했습니다. 나는 객체에 바인딩하지 않고 이름을 만들 수 있다고 생각하지 않기 때문에.
exec () 메소드를 사용하십시오. 예를 들어, 사전이 있고 각 사전을 원래 사전 값을 가진 변수로 바꾸고 싶다고 가정하면 다음을 수행 할 수 있습니다.
파이썬 2
>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
... exec("%s=%s" % (k,v))
>>> one
1
>>> two
2
파이썬 3
>>> c = {"one": 1, "two": 2}
>>> for k,v in c.items():
... exec("%s=%s" % (k,v))
>>> one
1
>>> two
2
전역 및 / 또는 로컬 네임 스페이스에 내용을 채우는 것은 좋지 않습니다. dict를 사용하는 것은 다른 언어 d['constant-key'] = value
입니다. 어색해 보입니다. 파이썬은 OO입니다. 주인의 말에 따르면 : "" "네임 스페이스는 훌륭한 아이디어입니다. 더 많은 것을 해보자!" ""
이처럼 :
>>> class Record(object):
... pass
...
>>> r = Record()
>>> r.foo = 'oof'
>>> setattr(r, 'bar', 'rab')
>>> r.foo
'oof'
>>> r.bar
'rab'
>>> names = 'id description price'.split()
>>> values = [666, 'duct tape', 3.45]
>>> s = Record()
>>> for name, value in zip(names, values):
... setattr(s, name, value)
...
>>> s.__dict__ # If you are suffering from dict withdrawal symptoms
{'price': 3.45, 'id': 666, 'description': 'duct tape'}
>>>
Keyword parameters allow you to pass variables from one function to another. In this way you can use the key of a dictionary as a variable name (which can be populated in your while
loop). The dictionary name just needs to be preceded by **
when it is called.
# create a dictionary
>>> kwargs = {}
# add a key of name and assign it a value, later we'll use this key as a variable
>>> kwargs['name'] = 'python'
# an example function to use the variable
>>> def print_name(name):
... print name
# call the example function
>>> print_name(**kwargs)
python
Without **
, kwargs
is just a dictionary:
>>> print_name(kwargs)
{'name': 'python'}
NOTE: This should be considered a discussion rather than an actual answer.
An approximate approach is to operate __main__
in the module you want to create variables. For example there's a b.py
:
#!/usr/bin/env python
# coding: utf-8
def set_vars():
import __main__
print '__main__', __main__
__main__.B = 1
try:
print B
except NameError as e:
print e
set_vars()
print 'B: %s' % B
Running it would output
$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1
But this approach only works in a single module script, because the __main__
it import will always represent the module of the entry script being executed by python, this means that if b.py
is involved by other code, the B
variable will be created in the scope of the entry script instead of in b.py
itself. Assume there is a script a.py
:
#!/usr/bin/env python
# coding: utf-8
try:
import b
except NameError as e:
print e
print 'in a.py: B', B
Running it would output
$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1
Note that the __main__
is changed to 'a.py'
.
vars()['meta_anio_2012'] = 'translate'
For free-dom:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
globkeys = globals().keys()
globkeys.append('globkeys') # because name 'globkeys' is now also in globals()
print 'globkeys==',globkeys
print
print "globals().keys()==",globals().keys()
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
del i
newnames = [ x for x in globals().keys() if x not in globkeys ]
print
print 'newnames==',newnames
print
print "globals().keys()==",globals().keys()
print
print '\n'.join(repr((u,globals()[u])) for u in newnames)
Result
globkeys== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', '__doc__', 'globkeys']
globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', 'globkeys', '__doc__']
newnames== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'kbutmzfgpcdqanrivwsxly', 'lxzmaysuornvdpjqfetbchgik', 'wznptbyermclfdghqxjvki', 'lwg', 'vsolxgkz', 'yobtlkqh']
globals().keys()== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'newnames', 'kbutmzfgpcdqanrivwsxly', '__builtins__', 'alphabet', 'random', 'lxzmaysuornvdpjqfetbchgik', '__package__', 'wznptbyermclfdghqxjvki', 'lwg', 'x', 'vsolxgkz', '__name__', 'globkeys', '__doc__', 'yobtlkqh']
('fztkebyrdwcigsmulnoaph', 't')
('umkfcvztleoij', 'p')
('kbutmzfgpcdqanrivwsxly', 'a')
('lxzmaysuornvdpjqfetbchgik', 'n')
('wznptbyermclfdghqxjvki', 't')
('lwg', 'j')
('vsolxgkz', 'w')
('yobtlkqh', 'c')
Another way:
import random
pool_of_names = []
for i in xrange(1000):
v = 'LXM'+str(random.randrange(10,100000))
if v not in globals():
pool_of_names.append(v)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print 'globals().keys()==',globals().keys()
print
for j in xrange(8):
globals()[pool_of_names[j]] = random.choice(alphabet)
newnames = pool_of_names[0:j+1]
print
print 'globals().keys()==',globals().keys()
print
print '\n'.join(repr((u,globals()[u])) for u in newnames)
result:
globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', 'i', 'v', '__name__', '__doc__', 'pool_of_names']
globals().keys()== ['LXM7646', 'random', 'newnames', 'LXM95826', 'pool_of_names', 'LXM66380', 'alphabet', 'LXM84070', '__package__', 'LXM8644', '__doc__', 'LXM33579', '__builtins__', '__name__', 'LXM58418', 'i', 'j', 'LXM24703', 'v']
('LXM66380', 'v')
('LXM7646', 'a')
('LXM8644', 'm')
('LXM24703', 'r')
('LXM58418', 'g')
('LXM84070', 'c')
('LXM95826', 'e')
('LXM33579', 'j')
'IT박스' 카테고리의 다른 글
힘내 : 커밋없이 작업 사본에 Cherry-Pick (0) | 2020.06.19 |
---|---|
어떤 Ruby IDE를 선호하십니까? (0) | 2020.06.19 |
왜 형식 인수로 NSInteger 변수를 캐스트해야합니까? (0) | 2020.06.19 |
Python 3 open (encoding =“utf-8”)을 Python 2로 백 포트 (0) | 2020.06.19 |
vim에서 명령 앨리어싱 (0) | 2020.06.19 |