prosource

루프에 있는 동안 다른 변수 이름을 어떻게 생성합니까?

probook 2023. 6. 12. 21:35
반응형

루프에 있는 동안 다른 변수 이름을 어떻게 생성합니까?

예를 들어...

for x in range(0,9):
    string'x' = "Hello"

그래서 저는 string1, string2, string3...모두 "안녕하세요"와 동등한.

물론 가능합니다. 사전이라고 합니다.

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

저는 이 말을 약간 견제하는 것처럼 말했지만, 실제로 한 값을 다른 값과 연결하는 가장 좋은 방법은 사전입니다.그것이 바로 그것을 위해 설계된 것입니다!

그건 정말 나쁜 생각입니다만...

for x in range(0, 9):
    globals()['string%s' % x] = 'Hello'

예를 들어 다음과 같습니다.

print(string3)

다음을 제공합니다.

Hello

하지만 이것은 나쁜 관행입니다.다른 사람이 제안하는 것처럼 사전이나 목록을 대신 사용해야 합니다.물론, 당신이 그것을 하는 방법을 정말 알고 싶어했지만, 그것을 사용하고 싶어하지 않았다면 말입니다.

이것을 할 수 있는 한 가지 방법은exec()예:

for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8

여기서 저는 파이썬 3.6+의 편리한 f 문자열 포맷을 활용하고 있습니다.

변수 이름을 만드는 것은 무의미합니다.왜요?

  • 이들은 불필요합니다.목록, 사전 등에 모든 것을 저장할 수 있습니다.
  • 생성하기가 어렵습니다.사용해야 합니다.exec또는globals()
  • 사용할 수 없습니다.이러한 변수를 사용하는 코드는 어떻게 작성합니까?사용해야 합니다.exec/globals()다시.

목록을 사용하는 것이 훨씬 쉽습니다.

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them
for x in range(9):
    exec("string" + str(x) + " = 'hello'")

이게 통할 겁니다.

사전 사용 안 함

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

이 작업을 수행하지 마십시오. 딕트를 사용합니다.

globals는 네임스페이스가 현재 가리키는 것을 제공하기 때문에 위험하지만 이것은 변경될 수 있으므로 globals에서 반환을 수정하는 것은 좋은 생각이 아닙니다.

목록이 필요합니다.

string = []
for i in range(0, 9):
  string.append("Hello")

이렇게 하면 9개의 "Hello"를 얻을 수 있으며 다음과 같이 개별적으로 얻을 수 있습니다.

string[x]

어디에x어떤 "안녕하세요"를 원하는지 확인할 수 있습니다.

그렇게,print(string[1])인쇄할 것입니다.Hello.

사전을 사용하는 것이 변수와 관련 값을 유지하는 올바른 방법이어야 하며 다음을 사용할 수 있습니다.

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

그러나 로컬 변수에 변수를 추가하려면 다음을 사용할 수 있습니다.

for i in range(9):
     exec('string%s = Hello' % i)

예를 들어 값 0 - 8을 할당하려는 경우 다음을 사용할 수 있습니다.

for i in range(9):
     exec('string%s = %s' % (i,i))

여기서의 과제는 글로벌을 방문하지 않는 것이라고 생각합니다().

개인적으로 (동적인) 변수를 저장할 목록을 정의한 다음 for 루프 내에 추가합니다.그런 다음 별도의 for 루프를 사용하여 각 항목을 보거나 다른 작업을 실행합니다.

다음은 예입니다. 다양한 지점에 여러 개의 네트워크 스위치(예: 2~8개)가 있습니다.이제 특정 지점에서 사용할 수 있는 스위치 수(또는 활성 ping 테스트)를 확인한 다음 해당 지점에서 몇 가지 작업을 수행해야 합니다.

내 코드는 다음과 같습니다.

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

출력:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07

언급URL : https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop

반응형