简体   繁体   中英

concat a varying value to a variable in python

instead of repeating the line multiple times can I concat a varying value in a variable so I change the variable after every iteration in a loop

ac2=AgglomerativeClustering(n_clusters = 2, affinity = 'euclidean', linkage = 'average')
ac3=AgglomerativeClustering(n_clusters = 3, affinity = 'euclidean', linkage = 'average')
ac4=AgglomerativeClustering(n_clusters = 4, affinity = 'euclidean', linkage = 'average')
ac5=AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'average')
ac6=AgglomerativeClustering(n_clusters = 6, affinity = 'euclidean', linkage = 'average')

is there a method using for loop to make this shorter something like this-

for i in range(2,7):
    ac+i=AgglomerativeClustering(n_clusters = i, affinity = 'euclidean', linkage = 'average')

you can use a dictionary

val = {}
for i in range(2,7):
  val["ac{0}".format(i)] = AgglomerativeClustering(n_clusters = i, affinity = 'euclidean', linkage = 'average')

print(val)

I would NOT RECOMMEND using the method below, but only for experimental purposes.

globals() returns dict of key as variabls and the value as the value assigned to the variable.

for i in range(2, 7):
    globals()[f'ac{i}'] = AgglomerativeClustering(n_clusters = i, affinity = 'euclidean', linkage = 'average')

It will create variables from ac2 to ac6 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM