0

I want to try and remove the quotes from my 2D array of lists but nothing is working, I've tried csv and the standard python functions but nothing appears to be working!!! Here's my code so far:

with open('level1.txt', 'r') as file:

            fileArr = file.readlines()
            fileArr = [[int(item) for item in line.rstrip("\n").split(",")] for line in fileArr]
            level.append(fileArr)
            print(str(level))

And here is what it outputs:

[[['platforms.GRASS_LEFT', '500', '500'], ['platforms.GRASS_MIDDLE', '570', '500'], ['platforms.GRASS_RIGHT', '640', '500'], ['platforms.GRASS_LEFT', '800', '400'], ['platforms.GRASS_MIDDLE', '870', '400'], ['platforms.GRASS_RIGHT', '940', '400'], ['platforms.GRASS_LEFT', '1000', '500'], ['platforms.GRASS_MIDDLE', '1070', '500'], ['platforms.GRASS_RIGHT', '1140', '500'], ['platforms.STONE_PLATFORM_LEFT', '1120', '280'], ['platforms.STONE_PLATFORM_MIDDLE', '1190', '280'], ['platforms.STONE_PLATFORM_RIGHT', '1260', '280'], ['platforms.GRASS_LEFT_BOTTOM', '-150', '600'], ['platforms.GRASS_LEFT', '535', '200'], ['platforms.GRASS_MIDDLE', '605', '200'], ['platforms.GRASS_RIGHT', '675', '200']]]

And finally this is what I want to be outputted:

[ [platforms.GRASS_LEFT, 500, 500],
                  [platforms.GRASS_MIDDLE, 570, 500],
                  [platforms.GRASS_RIGHT, 640, 500],
                  [platforms.GRASS_LEFT, 800, 400],
                  [platforms.GRASS_MIDDLE, 870, 400],
                  [platforms.GRASS_RIGHT, 940, 400],
                  [platforms.GRASS_LEFT, 1000, 500],
                  [platforms.GRASS_MIDDLE, 1070, 500],
                  [platforms.GRASS_RIGHT, 1140, 500],
                  [platforms.STONE_PLATFORM_LEFT, 1120, 280],
                  [platforms.STONE_PLATFORM_MIDDLE, 1190, 280],
                  [platforms.STONE_PLATFORM_RIGHT, 1260, 280],
                  [platforms.GRASS_LEFT_BOTTOM,-150,600],
                  [platforms.GRASS_LEFT,535,200],
                  [platforms.GRASS_MIDDLE,605,200],
                  [platforms.GRASS_RIGHT,675,200],
                  ]

Any help would be much appreciated to help stopping me having a mental breakdown.

3
  • 1
    The quotes are because they're strings and you want them to be ints (or some other numerical type). It might be easiest to leave them as strings in the list and convert them to some sort of number when you actually come to use them later in the code. Commented Dec 18, 2019 at 12:54
  • The code above does not produce this output, because calling int( "platforms.GRASS_LEFT" ) (line 3) will fail. The int() is not there in the version that produces a list of list of strings right? Commented Dec 18, 2019 at 21:18
  • Yeah, I lost the original code so this was the code that I had at the time. Commented Dec 20, 2019 at 11:51

3 Answers 3

1

There's a couple of ways to do this - I assume you actually want the data parsed, rather than only pretty-printed.

I'm not a fan of "pythonic" loops like:

fileArr = [[int(item) for item in line.rstrip("\n").split(",")] for line in fileArr]

The code is not so readable, and this form is completely frowned upon in C and C++ for() loops (yet somehow it championed in Python). Splitting the operations out into separate operations in a loop makes the code cleaner, more readable, and it runs in near-exactly the same time.

level = []
with open( "lines.txt", "rt" ) as fin:
    for line in fin:
        # TODO - handle exceptions in parsing
        location, x, y = line.split( ",", 2 )    # cut line into 3 pieces
        x = int( x )                             # convert string number into integer
        y = int( y )
        level.append( [ location, x, y ] )       # store a parsed copy

This gives the code a list of list items, where each item is a [ string, int, int ].

I don't know if the very specific formatting requirements are necessary, but they are fairly easily coded:

# Print the read level with specific indentation
indent = "                  "                       # some spaces
print( '[ ', end='' )
for i,item in enumerate( level ):
    if ( i > 0 ):
        print( indent, end='' )                     # print the indent (without new-line)
    print( "[%s, %d, %d]," % ( item[0], item[1], item[2] ) ) # print the 3 levels items
print( '%s]' % ( indent ) )
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is not that it prints with the quotes. The problem is that I want no quotes in the actual values. Using this solution still has the quotes present.
0

While others have mentioned how to get the integers as integers instead of strings, they have not mentioned how to get that first string "platforms.GRASS_MIDDLE" to read in as a variable. I strongly advise against trying to read in a value from a text file and evaluating that directly to get the variable value. If you are adamant you can look into the eval() function but that opens up a lot of possible issues.

Instead, you should have saved in your file a simple unique string ID, like say "GRASS_MIDDLE", then in your code have a function to transform these strings into the appropriate objects.

for obj in my_loaded_in_list:
    if obj[0] == "GRASS_MIDDLE":
        obj[0] = platforms.GRASS_MIDDLE
    if obj[0] == "GRASS_TOP":
           #......

This might get long if you have a lot of objects, having a dictionary of the unique string IDs and objects will make this smaller and nicer:

my_dictionary_pointing_unique_IDs_to_objects = dict()
my_dictionary_pointing_unique_IDs_to_objects["GRASS_MIDDLE"] = platforms.GRASS_MIDDLE
my_dictionary_pointing_unique_IDs_to_objects["GRASS_TOP"] = platforms.GRASS_TOP
#....


for obj in my_loaded_in_list:
    for key in my_dictionary_pointing_unique_IDs_to_objects:
        if key == obj[0]:
           obj[0] = my_dictionary_pointing_unique_IDs_to_objects[key]
           break

1 Comment

Thank you a lot, this along with some other code has helped me to finally solve this problem after so long.
0

I would try to split the first item of each list on the dot and then use getattr to get the value.

Like:

item = [platforms.GRASS_LEFT, 500, 500]
splitted_first_value = item[0].split('.')
item[0] = getattr(splitted_first_value[0], splitted_first_value[1])

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.