1

I have a very simple list where it looks like this:

['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']

What I would like to do is to split the values within each list where the values are displayed as follows:

[20,32,35,47,64,15,17,25,32,53,07,10,12,61,65,..]
myvallist = myvalues.split(" ")
print (myvallist)

For some reason, when I attempt to use the .split(), pyCharm is throwing an error.

Traceback (most recent call last):
  File "C:\Users\VFARETR.CENTRAL\Desktop\pyCharm\megaTest", line 25, in <module>
    myvallist = myvalues.split(" ")
AttributeError: 'list' object has no attribute 'split'

Any help would be great!

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
VJ1222
  • 21
  • 1

3 Answers3

0

You're trying to split the list, not the string. Try this:

input_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
complete_list = []
for sub_list in input_list:
    current_items = sub_list.split()
    complete_list.extend([i for i in current_items])
BTables
  • 4,413
  • 2
  • 11
  • 30
  • Unfortunately, none of the suggested solutions are working - which is a good thing in that I know I wasn't going crazy. and, to answer your question, it does not matter if it is a string or number - so long as I can query the list contents. – VJ1222 Sep 13 '21 at 15:55
  • 1
    Sounds like you have something else going on with your input data then. – BTables Sep 13 '21 at 16:05
  • Does the code from this answer do what you expect it to do, if you copy and paste it (including the hard-coded input)? If not, how is the result different from what you expect? If it does work, can you see something special about your input that causes a problem? – Karl Knechtel Sep 13 '21 at 16:21
  • complete_list = [] for sub_list in myvalues: current_items = sub_list.split() complete_list.extend([i for i in current_items]) ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68'] – VJ1222 Sep 13 '21 at 16:29
0

It says so because your list consists of strings. You have to acces the string inside the list before you split the string.

 mylist = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65',
          '08 14 31 58 68', '01 10 44 47 56']

myvallist = []

for item in mylist:
    myvallist += item.split(' ')  # adds the numbers of the current string to myvallist

print(myvallist)
ph140
  • 478
  • 3
  • 10
0

I don't know if you want the entries to be integers or strings but here's a solution with them as strings.

my_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']

my_new_list = [item for sublist in [item.split(" ") for item in my_list] for item in sublist]

The inner list comprehension splits each string by spaces and then the outer list comprehension then flattens the array produced.