Removing single quotes from multiple data type 2D Array python
python for loop
python data structures
python variable type check
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.
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 == "GRASS_MIDDLE": obj = platforms.GRASS_MIDDLE if obj == "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: obj = my_dictionary_pointing_unique_IDs_to_objects[key] break
3. Strings, Lists, Arrays, and Dictionaries — PyMan 0.9.31 , Core Python has an array data structure, but it's not nearly as versatile, but the elements of dictionaries are accessed in a different way than for lists. Any character that you can type from a computer keyboard, plus a variety of Caution : the quotes defining a given string must both be single or both be double quotes. Python arrays are homogenous data structure. They are used to store multiple items but allow only the same type of data. They are available in Python by importing the array module. Lists, a built-in type in Python, are also capable of storing multiple values. But they are different from arrays because they are not bound to any specific type.
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, item, item ) ) # print the 3 levels items print( '%s]' % ( indent ) )
Python Data Types with Python, This guide is an overview of Python Data Types. Python uses single quotes ' double quotes " and triple quotes """ to Python can use a special syntax to format multiple strings and In the following example, the MyTable variable is a two-dimensional array : Elements cannot be removed from a tuple. Multidimensional arrays in Python provides the facility to store different type of data into a single array ( i.e. in case of multidimensional list ) with each element inner array capable of storing independent data from the rest of the array with its own length also known as jagged array, which cannot be achieved in Java, C, and other languages.
I would try to split the first item of each list on the dot and then use
getattr to get the value.
item = [platforms.GRASS_LEFT, 500, 500] splitted_first_value = item.split('.') item = getattr(splitted_first_value, splitted_first_value)
5. Data Structures — Python 3.3.7 documentation, The list data type has some more methods. If no index is specified, a.pop() removes and returns the last item in the list. transposed =  >>> for i in range(4 ): transposed.append([row[i] for row in matrix]) . Note that multiple assignment is really just a combination of tuple packing and sequence� This term refers to the transformation of data into a series of bytes (hence serial) to be stored or transmitted across a network. To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object, so it makes easy to write data to files. See the following table
Built-in Types — Python 3.8.5 documentation, Objects of different types, except different numeric types, never compare equal. A comparison between numbers of different types behaves as though the exact values of those numbers were Return the integer represented by the given array of bytes. >>> Triple quoted: '''Three single quotes''' , """Three double quotes""". The new created array is : 1 2 3 1 5 The popped element is : 3 The array after popping is : 1 2 1 5 The array after removing is : 2 1 5 Slicing of a Array In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation .
Python, Python | Ways to Convert a 3D list into a 2D list � Triple quotes in Python � Single and Double Quotes | Python � Print lists in Python (4 Different� Strings are sequences of character data. The string type in Python is called str. String literals may be delimited using either single or double quotes. All the characters between the opening delimiter and matching closing delimiter are part of the string: >>> >>>
Data Structures: Python Tutorial, Abstract Data Type and Data Structures; Primitive Data Structures by enclosing a sequence of characters within a pair of single or double quotes. multi_arr_ones = np.ones((3,4)) # Creating 2D array with 3 rows and 4 columns However, Python provides many different flavours of data collection� Arrays are data structures which hold multiple values. Python does not have arrays but it has lists. Lists are mutable collections of objects. This is an example: Code: values=['milk','cheese',12, False] Lists are ordered. We can index them and access values. We will see how to do this in the next heading. Lists are heterogeneous. A list can
- 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.
- 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?
- Yeah, I lost the original code so this was the code that I had at the time.
- Thank you a lot, this along with some other code has helped me to finally solve this problem after so long.
- 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.