DNZ
DNZ

Reputation: 37

Convert loop output to a list python

I have this loop:

features = ['ca','tf','se','zz','rd','fbs','th','ex']
for i in range(1, len(features) + 1):  # iterate and select next features
    Sbest = [] 
    input_f = features[:i]
    y = data['target']
    X = data[input_f] 
    model_= KMeans(n_clusters=2, random_state=0, init='k-means++', n_init=10, max_iter=100)
    model_.fit(X)
    precision,recall,fscore,support=score(y,model_.labels_,average='macro')
    Sbest.append(input_f)
    Sbest.append(round(fscore,2))
    print(Sbest)

that gives me this output:

[['ca'], 0.62]
[['ca', 'tf'], 0.62]
[['ca', 'tf', 'se'], 0.71]
[['ca', 'tf', 'se', 'zz'], 0.71]
[['ca', 'tf', 'se', 'zz', 'rd'], 0.42]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs'], 0.12]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th'], 0.56]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th', 'ex'], 0.56]

but what I really want is that output could be a list as I want to sort it later; What I want is something like this:

[
[['ca'], 0.62],
[['ca', 'tf'], 0.62],
[['ca', 'tf', 'se'], 0.71],
[['ca', 'tf', 'se', 'zz'], 0.71],
[['ca', 'tf', 'se', 'zz', 'rd'], 0.42],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs'], 0.12],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th'], 0.56],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th', 'ex'], 0.56]
]

How do I convert this to a list?

Upvotes: 0

Views: 108

Answers (2)

jmaloney13
jmaloney13

Reputation: 235

I'd suggest that outside of/before the for loop, you create an empty list

a = []

Then at the end of the for loop, immediately before or after the print(sbest) you add a line for

a.append(sbest)

Upvotes: 2

Shunya
Shunya

Reputation: 2474

One easy thing you could do is creating a list outside the loop and appending each of your Sbest lists to it.

Something like this:

my_list = []
features = ['ca','tf','se','zz','rd','fbs','th','ex']
for i in range(1, len(features) + 1):  # iterate and select next features
    Sbest = [] 
    input_f = features[:i]
    y = data['target']
    X = data[input_f] 
    model_= KMeans(n_clusters=2, random_state=0, init='k-means++', n_init=10, max_iter=100)
    model_.fit(X)
    precision,recall,fscore,support=score(y,model_.labels_,average='macro')
    Sbest.append(input_f)
    Sbest.append(round(fscore,2))
    print(Sbest)
    my_list.append(Sbest)
print(my_list)

Upvotes: 1

Related Questions