0

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?

4
  • What is the code? Commented Feb 20, 2021 at 8:35
  • Just put it into a list a = [a] Commented Feb 20, 2021 at 8:37
  • @ti7, I tried, it doen't help. Commented Feb 20, 2021 at 8:44
  • 1
    what about a=[]; a.append(sbest) ? Commented Feb 20, 2021 at 8:47

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.