How to read lists and int from a file? [closed] - python
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a coding system based on Enigma but I'd like to add a twist to it. In order to make to program customizable by the user id like to create "files" wich contains parameters that my prgramm will use to then crypt the message. It includes lists as well as integers. How can I read them?
I have tried using a split method and seperating my lists with "/" but the lists are considered as strings.
Here is an example of the paramaters I would like to assign to, in order, list1, list2, list3, list4, trigger1, trigger2, trigger3 that I tried to seperate with "/":
[6,18,20,12,17,26,19,4,10,22,13,7,14,1,21,9,2,16,3,23,24,8,15,11,25,5]/[1,-5,6,3,-4,2,-4,-4,-3,5,-1,1,-2,-2,-1,3,4,2,5,-4,-4,-4,2,-2,1,5]/[5,-1,-1,-1,-1,1,4,-3,-1,4,1,1,-4,2,-5,4,0,-3,-1,1,-2,0,2,2,-1,-3]/[2,-1,2,0,-3,2,-1,-1,0,2,-1,2,-2,-1,1,4,2,0,-2,-5,2,-1,3,0,-3,-1]/11/5/17
f=open("param.txt")
param=f.read()
list_tbl,param=param.split("/",1)
list_pattern1,param=param.split("/",1)
list_pattern2,param=param.split("/",1)
list_pattern3,param=param.split("/",1)
trigger1,param=param.split("/",1)
trigger2,param=param.split("/",1)
trigger3=param
When I try using the lists, they cannot be used because they are strings.
Have a look at ast.literal_eval which will basically do what you want i.e. make a list out of a string such as this:
from ast import literal_eval
my_string = '[0, 1, 2, 3]'
my_list = literal_eval(my_string)
To create multiple variables you can use a dictionary instead and then just fetch it by a key e.g.:
my_dict = {}
for i in range(10):
my_dict['list' + str(i)] = <some value>
which is definitely prettier than wasting lines on creating each variable.
Related
How can i zip() two lists together without the output having "\n" at the beginning of every second element? [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 13 days ago. Improve this question I currently have two lists songlist = [] artistlist = [] I return list(zip(songlist, artistlist)) and it gives me what I want(a 3d list of a 2d list containing each song title and respective artist) but before each second item in each list is "\n" for example a list in the 3d list would look like: ["Amarillo By Morning","\nGeorge Strait"] I'm gonna be using the artist in a later function so I'd rather there not be the \n there. instead of my above code i tried returning a variable containing: [i + j for i, j in zip(songlist, artistlist)] but that just returned: ["Amarillo By Morning\nGeorge Strait", ... cont.
To avoid making another iterator, you can just modify each artist as they come along, if you can't modify it at the source. Also, return a list instead of using string concatenation if you want a list. [[song, artist.strip()] for song, artist in zip(songlist, artistlist)]
Use the strip() method to remove the whitespace characters from the start and the end of the string (including the new line characters) : zipped_list = list(zip([song.strip() for song in songlist], [artist.strip() for artist in artistlist]))
I CANNOT get rid of brackets when trying to print these lists for some reason [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 22 days ago. Improve this question I have tried most methods but for some reason it just does not want to print without the brackets. Why is that??
It means that list1 and/or list2 are lists of lists. Try: for x in list1: print(x[0]) for y in list2: print(y[0])
Hey reffering to the first answer which i really liked, it makes you use indexing which i dont really like in my code writing in python. The complete solution without using any external library or indexing is to use a nested for loop, if it is really a list of lists use the function like so: def printMe(self): for list in list1: for x in list: print(x) and the same for the second list, I was able to repredouce your work and it worked, i wouldve used also more parsing in the strings but it is your own choice, Hope it helped :)
It is probably caused by an extra axis. Try this: for x in list1[0]: print(x)
If you want to just print the list without square brackets use the command: print(*x,sep=" ")
When would using the filter function be used instead of a list comprehension? [closed]
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 2 years ago. Improve this question Recently, I have learned a bit about the filter method, an alternative to using list comprehensions. Say I have a list as such: names = ["Bob", "Billy", "Samuel", "Adam", "Rob"] Now, I would like to get a list containing the names that start with the letter, "B". I could go about this in a couple of ways. This is one: b_starting_names = list(filter(lambda name: name.startswith("B"), names)) This is another: b_starting_names = [name for name in names if name.startswith("B")] Could someone please explain what the difference is between a list comprehension and the filter function, and why someone may want to use one over the other?
There's no harm in using either. A similar comment can be made about map. I tend to use whatever one feels easier to read. In your case I would avoid using the lambda as it is a bit verbose, and instead use the comprehension. I would use filter or map methods if I already had a function existing I could just pass to the method, which would be more terse than the comprehension. For example, say I write a program for finding the length of the largest name: # Using map longest = max(map(len, names)) # Using generator expression longest = max(len(name) for name in names)) In the above example I would choose map over the generator expression, but it's entirely personal preference.
Search and Replace a word within a word in Python. Replace() method not working [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 4 years ago. Improve this question How do I search and replace using built-in Python methods? For instance, with a string of appleorangegrapes (yes all of them joined), Replace "apple" with "mango". The .replace method only works if the words are evenly spaced out but not if they are combined as one. Is there a way around this? I searched the web but again the .replace method only gives me an example if they are spaced out. Thank you for looking at the problem!
This works exactly as expected and advertised. Have a look: s = 'appleorangegrapes' print(s) # -> appleorangegrapes s = s.replace('apple', 'mango') print(s) # -> mangoorangegrapes The only thing that you have to be careful of is that replace is not an in-place operator and as such it does not update s automatically; it only creates a new string that you have to assign to something. s = 'appleorangegrapes' s.replace('apple', 'mango') # the change is made but not saved print(s) # -> appleorangegrapes
replace can work for any string, why you think that it doesn't, here is the test: >>> s='appleorangegrapes' >>> s.replace('apple','mango') 'mangoorangegrapes' >>> Don't you see that you received your expected result?
Can't edit a tuple from inside a function [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 7 years ago. Improve this question I am programming an application in python. Here is the function: def aircraftListBoxRefresh(): sqlConnect=sqlite3.connect("fglconfdb") sqlCursor=sqlConnect.cursor() sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig") adl=sqlCursor.fetchall() global aircraftDirectories for x in adl: aircraftDirectories=aircraftDirectories+(x,) I put print(aircraftDirectories) to test whether the value changes. It changes in side the function. But outside the function it is null. I am trying to access the value with this: aircraftDirectories=() aircraftDir=StringVar(value=aircraftDirectories) aircraftListBox=Listbox(mainframe,height=7,width=100,listvariable=aircraftDir) aircraftListBox.place(x=170,y=170) But I can't. Any help greatly appreciated. Regards.
You can't modify tuples anywhere, inside a function or outside, they're immutable. Maybe you want lists: def aircraftListBoxRefresh(): sqlConnect=sqlite3.connect("fglconfdb") sqlCursor=sqlConnect.cursor() sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig") adl=sqlCursor.fetchall() for x in adl: aircraftDirectories.append(x) aircraftDirectories=[] aircraftDir=StringVar(value=aircraftDirectories) aircraftListBox=Listbox(mainframe,height=7,width=100,listvariable=aircraftDir) aircraftListBox.place(x=170,y=170) With this approach, since you're modifying the list and not re-assigning to the variable, you don't need global.
You can't modify a tuple, but you can replace it. In this example M[] is a list of tuples, each tuple contains two numbers. I want to replace the first number of a tuple to 0, but keep the second number. M[j] = (0, M[j][1])