1

I have problems with merging lists into a list

The followings are what I have tried

import os,glob
from PIL import Image
from skimage import io
import numpy as np
from statistics import stdev 

path = "/Users/Xin/Desktop/SVM-Image-Classification-master/test"
# Delete images with the low pixel value
for filename in os.listdir(path):
    images = Image.open(os.path.join(path,filename))  
    value = [round(np.mean(images).tolist(),2)]
    print(value)
    print(type(value))
    #if np.mean(images) < 20:
        #os.remove(os.path.join(path, filename))
#print(len(os.listdir(path)))

The output as follows

[12.69]
<class 'list'>
[14.46]
<class 'list'>
[12.25]
<class 'list'>
[9.51]
<class 'list'>
[18.7]
<class 'list'>
[10.0]
<class 'list'>
[18.13]
<class 'list'>
[12.63]
<class 'list'>

What I need is merging the above lists into a list so that I can do sum() function to get a total value

Can anyone give me a help? Thanks

Xin Zhang
  • 29
  • 4
  • 2
    You can define a list and keep appending the value in it and print/return `sum(list)` – badri Apr 10 '19 at 22:09
  • Possible duplicate of [How do I concatenate two lists in Python?](https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python) – patyx Apr 10 '19 at 22:17
  • Does `value = round(np.mean(images),2)` work for you? I don't think you need the `tolist` and outer brackets. – hpaulj Apr 10 '19 at 22:27

2 Answers2

1

Try following way

from numpy import array
from numpy import sum
sum_list = []
for filename in os.listdir(path):
    images = Image.open(os.path.join(path,filename))  
    value = [round(np.mean(images).tolist(),2)]
    sum_list.append(value)
v = array(sum_list)
return sum(v)
badri
  • 438
  • 3
  • 11
  • will not work as you are appending a list to sum_list which in effect will cause an error during `sum(sum_list)` – Marcin Apr 10 '19 at 22:21
  • The only thing I cann't understand is why do we need square brackets in `value = [ .... ]`; drop it, e.g. `value = round(np.mean(images), 2)` and life becomes much easier... – bubble Apr 10 '19 at 23:14
0

Create a list that will store all of the values, then append to it:

all_values = []
for filename in os.listdir(path):
    images = Image.open(os.path.join(path,filename))  
    value = [round(np.mean(images).tolist(),2)]
    all_values = [*all_values, *value]

print(all_values)
Marcin
  • 184
  • 1
  • 2
  • 12