Re: 'string.join' is wrong in my Python console
On Thursday, December 3, 2015 at 12:40:52 PM UTC+5:45, Robert wrote: > Hi, > > I read the tutorial on "Why is join() a string method instead of a list > or tuple method?" > at link: > https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls > > I have a problem on running the last line: > --- > If none of these arguments persuade you, then for the moment you can > continue to use the join() function from the string module, which allows > you to write > > string.join(['1', '2', '4', '8', '16'], ", ") > --- > > My Python console is 2.7. It should be no problem because I see the tutorial > is 2.7 too. > > The console has these display: > > string.join(['1', '2', '4', '8', '16'], ", ") > --- > NameError Traceback (most recent call last) > in () > > 1 string.join(['1', '2', '4', '8', '16'], ", ") > > NameError: name 'string' is not defined > > > From the context, I don't see string should be replaced by something else. > > Could you tell me why I have such an error? > > > Thanks, simply, import string at the beginning of your script. -- https://mail.python.org/mailman/listinfo/python-list
Re: storing test logs under /var/log/
On 03Dec2015 12:20, Ganesh Pal wrote: I would need few tips from your past experiences on how to store the test logs My requirement is to capture log under /var/log/ directory every time the test is run . Normally /var/log itself is only writable by root. Unless you are running your tests as root (_not_ recommended unless you're testing something quite privileged) the convention is either to create a log directory in the home directory of the user running the tests (though not if running as root), *or* to create a subdirectory in /var/log named after your purpose, eg /var/log/test-results. The test will create one small log files which are around 1KB in size . Fine, unless you're running some poor filesystem (unlikely these days). Here is how I plan to approach this , create directory based on current timesamp and store the logs in it . Sounds reasonable to me, but definitiely inside a top level directory _below_ /var/log. Sample code : time_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "/" LOG_DIR = "" + time_now This is a little weird in a few ways. Firstly, UPPER_CASE names are normally reserved for what would be called "constants" in languages like C: top level global names for program wide defaults. You don't use them for working, changable, names like the computed name of your log directory. I'd be saying something like this: # near the top of your program TOP_LOG_DIR = '/var/log/test-results' # lower down when computing the subdirectory for this test run time_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') results_dir = os.path.join(TOP_LOG_DIR, time_now) Notice also that this example code does not mention the '/'; on UNIX of course that is the path separator, and /var/log is a UNIX thing, but generally you should not unnecessarily put in system depending stuff like '/' (vs '\' on say Windows) in the middle of your code. So use os.path.join to construct pathnames. try: retcode = os.makedirs(LOG_DIR) if retcode: raise Exception( "Faild to create log directory. mkdir %s failed !!!" % LOG_DIR) except Exception, e: sys.exit("Failed to create log directory...Exiting !!!") 1. Do I need to add the cleanup code to remove the log directory say /var/log/test_log/2015-11-25_04-07-48/ , because we might have many more directories like this when test are run multiple times , Iam avoiding because the test will be run 2/3 times max and file sizes are also very small I would also avoid it. I would leave that as an entirely separate task for another program (quite possibly a shell script whose sole purpose it to tidy up things like that). That way a user can safel;y run your test program _without_ being in fear that it my, unasked, delete a whole bunch of earlier tests data. Having your test program "clean up" is effectively wiring in a policy decision into your program, where users cannot avoid or change it. All programs implement some policy (arbitrary decisions about things beyond their core purpose, such as tidyup of data they did not create), but that should be minimised; that way the users can decide on policy themselves. 2. Any better suggestion for my use case. I would change your try/except code above a little: os.makedirs does not return zero/nonzero on success/failure like a C library function, it raises an exception. So remove your if statement, changing this: retcode = os.makedirs(LOG_DIR) if retcode: raise Exception( "Faild to create log directory. mkdir %s failed !!!" % LOG_DIR) into: os.makedirs(results_dir) # see earlier code Also, you discard the value "e" of the exception. It is almost always best to report exceptions tso that the user can figure out what went wrong, not merely to know that something (unidentified) went wrong. And because os.makedirs raises an except, and the default behaviour of a python program (without a try/except) is the abort with a nonzero exit and _also_ helpfully report the whole exception and the code which caused it, you could completely discard your whole try/except! Finally. sys.exit accepts an integer, not a string. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- My Python console is 2.7. It should be no problem because I see the tutorial is 2.7 too. The console has these display: string.join(['1', '2', '4', '8', '16'], ", ") --- NameError Traceback (most recent call last) in () > 1 string.join(['1', '2', '4', '8', '16'], ", ") NameError: name 'string' is not defined From the context, I don't see string should be replaced by something else. Could you tell me why I have such an error? You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Gary Herron Thanks, -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Is Microsoft Windows secretly downloading childporn to your computer ?!
On 03/12/15 07:24, Chris in Makati wrote: > On Wed, 2 Dec 2015 08:57:44 + (UTC), Juha Nieminen > wrote: > >> In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> It's a matter of perspective. If a hacker breaks into your computer and >> starts a download from somewhere else into your computer, isn't the hacker >> "downloading" things to your computer? > > Does it matter? As far as the law is concerned, it is possession of > child porn that's illegal. How it got there is irrelevant. > You are posting to a wide range of international newsgroups (with this thread being way off-topic for all of them...). It makes no sense to talk about "the law", because this is not something covered by /international/ law. What counts as "child porn", what counts as "possession", how relevant intention, knowledge, etc., is, varies enormously from country to country. Even if the OP is telling the truth (and if Skybuck said that grass is green, I'd recommend going outside to check), and he gets caught with this stuff on his machine, punishments can vary from "it's fine as long as you don't distribute it" to "25 years for each picture, to be served consecutively". -- https://mail.python.org/mailman/listinfo/python-list
Re: static variables
Op 02-12-15 om 21:30 schreef Ian Kelly: > A person can hold one opinion in some contexts and an opposing opinion > in others. Yes people are capable of that. It doesn't mean we shouldn't challenge them on that. There are many possibilities for people to act like that. One context can be sufficiently different from the other to support a different opinion, people can be hypocritical, they can have different preference in different contexts, they can be biased, they can be in a different mood, there may be some misunderstanding. Aren't we allowed to probe for what is behind these opposing opinions? I know people who will defend a teacher leading a class in prayer in one context and several months later fight it in an other context. The difference being that in the first context the teacher's faith is compatible with there own and in the second context it isn't. When others challenge them on that and point this out, do you consider it an adequate response should they react with the quote: A foolish consistency is the hobgoblin of little minds. My opinion is that if one finds oneself in the situation that one comes to different opinions in different contexts, one should try to find out on what grounds one does so. And not let possible biases, misunderstandings, ... go unchallenged. I also see nothing wrong with challenging someone's view when you notice something like this is going on with them. But that seems to be something the regulars here have problems with because all too often they respond with the above quote and react as if that settles the question. -- Antoon. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is Microsoft Windows secretly downloading childporn to your computer ?!
On Thu, Dec 3, 2015 at 8:00 PM, David Brown wrote: > Even if the OP is telling the truth (and if Skybuck said that > grass is green, I'd recommend going outside to check) Here in Australia, we're coming up on summer, so grass is more likely to be yellowish-brown. Definitely don't believe people who claim it's green. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Is Microsoft Windows secretly downloading childporn to your computer ?!
In comp.lang.c++ Chris in Makati wrote: > On Wed, 2 Dec 2015 08:57:44 + (UTC), Juha Nieminen > wrote: > >>In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >>It's a matter of perspective. If a hacker breaks into your computer and >>starts a download from somewhere else into your computer, isn't the hacker >>"downloading" things to your computer? > > Does it matter? As far as the law is concerned, it is possession of > child porn that's illegal. How it got there is irrelevant. Most judiciary systems are not robots following a narrow set of instructions. If they determine that it wasn't your fault, they will not punish the innocent. Besides, how would they even know what's in your computer? --- news://freenews.netfront.net/ - complaints: n...@netfront.net --- -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
Thank you for your suggestion. This will help a lot. On 2015-12-03 08:32 Jussi Piitulainen wrote: > list = [ item for item in list > if ( 'Banana' not in item and > 'Car' not in item ) ] I often saw constructions like this x for x in y if ... But I don't understand that combination of the Python keywords (for, in, if) I allready know. It is to complex to imagine what there really happen. I understand this for x in y: if ... But what is about the 'x' in front of all that? -- GnuPGP-Key ID 0751A8EC -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On Thu, Dec 3, 2015 at 8:27 PM, wrote: > Thank you for your suggestion. This will help a lot. > > On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. > > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? It's called a *list comprehension*. The code Jussi posted is broadly equivalent to this: list = [] for item in list: if ( 'Banana' not in item and 'Car' not in item ): list.append(item) I recently came across this blog post, which visualizes comprehensions fairly well. http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ The bit at the beginning (before the first 'for') goes inside a list.append(...) call, and then everything else is basically the same. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On 03.12.2015 10:27, c.bu...@posteo.jp wrote: > > I often saw constructions like this >x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. > > I understand this >for x in y: > if ... > > But what is about the 'x' in front of all that? > The leading x states which value you want to put in the new list. This may seem obvious in the simple case, but quite often its not the original x-ses found in y that you want to store, but some transformation of it, e.g.: [x**2 for x in y] is equivalent to: squares = [] for x in y: squares.append(x**2) -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
In a message of Thu, 03 Dec 2015 10:27:19 +0100, c.bu...@posteo.jp writes: >Thank you for your suggestion. This will help a lot. > >On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > >I often saw constructions like this > x for x in y if ... >But I don't understand that combination of the Python keywords (for, >in, if) I allready know. It is to complex to imagine what there really >happen. > >I understand this > for x in y: >if ... > >But what is about the 'x' in front of all that? This is a list comprehension. see: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions But I would solve your problem like this: things_I_do_not_want = ['Car', 'Banana', ] things_I_want = [] for item in list_of_everything_I_started_with: if item not in things_I_do_not_want: things_I_want.append(item) Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On 12/03/2015 10:27 AM, c.bu...@posteo.jp wrote: I often saw constructions like this x for x in y if ... But I don't understand that combination of the Python keywords (for, in, if) I allready know. It is to complex to imagine what there really happen. I understand this for x in y: if ... But what is about the 'x' in front of all that? I'd advise you insist on understanding this construct as it is a very common (and useful) construct in python. It's a list comprehension, you can google it to get some clues about it. consider this example [2*i for i in [0,1,2,3,4] if i%2] == [2,6] you can split it in 3 parts: 1/ for i in [0,1,2,3,4] 2/ if i/2 3/ 2*i 1/ I'm assuming you understand this one 2/ this is the filter part 3/ this is the mapping part, it applies a function to each element To go back to your question "what is about the 'x' in front of all that". The x is the mapping part, but the function applied is the function identity which simply keeps the element as is. # map each element, no filter [2*i for i in [0,1,2,3,4]] == [0, 2, 4, 6, 8] # no mapping, keeping only odd elements [i for i in [0,1,2,3,4] if i%2] == [1,3] JM -- https://mail.python.org/mailman/listinfo/python-list
Re: python message
On 2015-12-02, jorge.conr...@cptec.inpe.br wrote: > I do not understand this message. Atached it my code. I'm new to Usenet, so maybe it's my fault. But I can't find any attachment in your message. Would you mind to post the code? -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
Laura Creighton wrote: > In a message of Thu, 03 Dec 2015 10:27:19 +0100, c.bu...@posteo.jp writes: >>Thank you for your suggestion. This will help a lot. >> >>On 2015-12-03 08:32 Jussi Piitulainen wrote: >>> list = [ item for item in list >>> if ( 'Banana' not in item and >>> 'Car' not in item ) ] >> >>I often saw constructions like this >> x for x in y if ... >>But I don't understand that combination of the Python keywords (for, >>in, if) I allready know. It is to complex to imagine what there really >>happen. >> >>I understand this >> for x in y: >>if ... >> >>But what is about the 'x' in front of all that? > > This is a list comprehension. > see: > https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions > > But I would solve your problem like this: > > things_I_do_not_want = ['Car', 'Banana', ] > things_I_want = [] > > for item in list_of_everything_I_started_with: > if item not in things_I_do_not_want: >things_I_want.append(item) Note that unlike the original code your variant will not reject "Blue Banana". If the OP wants to preserve the '"Banana" in item' test he can use for item in list_of_everything_I_started_with: for unwanted in things_I_do_not_want: if unwanted in item: break else: # executed unless the for loop exits with break things_I_want.append(item) or things_I_want = [ item for item in list_of_everything_I_started_with if not any(unwanted in item for unwanted in things_I_do_not_want) ] -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
writes: > Thank you for your suggestion. This will help a lot. > > On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. Others have given the crucial search word, "list comprehension". The brackets are part of the notation. Without brackets, or grouped in parentheses, it would be a generator expression, whose value would yield the items on demand. Curly braces would make it a set or dict comprehension; the latter also uses a colon. > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? You can understand the notation as collecting the values from nested for-loops and conditions, just like you are attempting here, together with a fresh list that will be the result. The "x" in front can be any expression involving the loop variables; it corresponds to a result.append(x) inside the nested loops and conditions. Roughly: result = [] for x in xs: for y in ys: if x != y: result.append((x,y)) ==> result = [(x,y) for x in xs for y in ys if x != y] On python.org, this information seems to be in the tutorial but not in the language reference. -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On 03/12/15 02:15, c.bu...@posteo.jp wrote: I would like to know how this could be done more elegant/pythonic. I have a big list (over 10.000 items) with strings (each 100 to 300 chars long) and want to filter them. list = . for item in list[:]: if 'Banana' in item: list.remove(item) if 'Car' in item: list.remove(item) There are a lot of more conditions of course. This is just example code. It doesn't look nice to me. To much redundance. btw: Is it correct to iterate over a copy (list[:]) of that string list and not the original one? No idea how 'Pythonic' this would be considered, but you could use a combination of filter() with a regular expression : # -- import re list = ... pattern = re.compile( r'banana|car', re.I ) filtered_list = filter( lambda line: not pattern.search(line), list ) # -- HTH -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On 03/12/2015 01:15, c.bu...@posteo.jp wrote: I would like to know how this could be done more elegant/pythonic. I have a big list (over 10.000 items) with strings (each 100 to 300 chars long) and want to filter them. list = . for item in list[:]: if 'Banana' in item: list.remove(item) if 'Car' in item: list.remove(item) There are a lot of more conditions of course. This is just example code. It doesn't look nice to me. To much redundance. targets = ['Banana', 'Car'...] for item in list[:]: for target in targets: if target in item: list.remove(item) btw: Is it correct to iterate over a copy (list[:]) of that string list and not the original one? Absolutely :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Are there any plans to support nCurses 6.0 with Python?
The GNU Project has announced the release of nCurses 6.0. With it, Python curses would be able to support 256 colors instead of the current 8 or 16. I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is not usable by Python programs, such as my character-mode emulation of pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates a 71 color palette but will not work (its has been disabled) with the existing 16-color curses because text attributes (such as underline) partially overlay the foreground-background color-pair attributes. -- https://mail.python.org/mailman/listinfo/python-list
Re: Are there any plans to support nCurses 6.0 with Python?
On 03/12/2015 12:30, eclectic...@gmail.com wrote: The GNU Project has announced the release of nCurses 6.0. With it, Python curses would be able to support 256 colors instead of the current 8 or 16. I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is not usable by Python programs, such as my character-mode emulation of pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates a 71 color palette but will not work (its has been disabled) with the existing 16-color curses because text attributes (such as underline) partially overlay the foreground-background color-pair attributes. Work is all ready being done to support building Python with ncurses6, see https://bugs.python.org/issue25720. Whether this alone meets your needs or an enhancement request on the bug tracker against 3.6 is required I'm really not qualified to say. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On Thu, 03 Dec 2015 08:32:49 +0200, Jussi Piitulainen wrote: > def isbad(item): > return ( 'Banana' in item or > 'Car' in item ) > > def isgood(item) > return not isbad(item) badthings = [ 'Banana', 'Car', ] def isgood(item) for thing in badthings: if thing in item: return False return True -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
Denis McMahon writes: > On Thu, 03 Dec 2015 08:32:49 +0200, Jussi Piitulainen wrote: > >> def isbad(item): >> return ( 'Banana' in item or >> 'Car' in item ) >> >> def isgood(item) >> return not isbad(item) > > badthings = [ 'Banana', 'Car', ] > > def isgood(item) > for thing in badthings: > if thing in item: > return False > return True As long as all conditions are of that shape. -- https://mail.python.org/mailman/listinfo/python-list
getting fileinput to do errors='ignore' or 'replace'?
I'm having trouble with some input files that are almost all proper UTF-8 but with a couple of troublesome characters mixed in, which I'd like to ignore instead of throwing ValueError. I've found the openhook for the encoding for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): do_stuff(line) which the documentation describes as "a hook which opens each file with codecs.open(), using the given encoding to read the file", but I'd like codecs.open() to also have the errors='ignore' or errors='replace' effect. Is it possible to do this? Thanks. -- Why is it drug addicts and computer afficionados are both called users? --- Clifford Stoll -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 2015-12-03, Adam Funk wrote: > I'm having trouble with some input files that are almost all proper > UTF-8 but with a couple of troublesome characters mixed in, which I'd > like to ignore instead of throwing ValueError. I've found the > openhook for the encoding > > for line in fileinput.input(options.files, > openhook=fileinput.hook_encoded("utf-8")): > do_stuff(line) > > which the documentation describes as "a hook which opens each file > with codecs.open(), using the given encoding to read the file", but > I'd like codecs.open() to also have the errors='ignore' or > errors='replace' effect. Is it possible to do this? I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different machines). -- ...the reason why so many professional artists drink a lot is not necessarily very much to do with the artistic temperament, etc. It is simply that they can afford to, because they can normally take a large part of a day off to deal with the ravages.--- Amis _On Drink_ -- https://mail.python.org/mailman/listinfo/python-list
Re: Does Python 2.7 do Open Office
On Thu, 3 Dec 2015 00:47:42 +, MRAB wrote: >On 2015-12-02 23:50, Seymore4Head wrote: >> I have a text file I would like to search through but I have tried it >> before. I don't remember why they are not compatible together, but I >> wanted to ask to make sure. >> >> I know I can convert the file to plain text but it would be nice not >> to have to do that. >> >A quick search found this: > >https://wiki.openoffice.org/wiki/Python Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
Am 03.12.2015 um 10:02 schrieb Gary Herron: On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- My Python console is 2.7. It should be no problem because I see the tutorial is 2.7 too. The console has these display: string.join(['1', '2', '4', '8', '16'], ", ") --- NameError Traceback (most recent call last) in () > 1 string.join(['1', '2', '4', '8', '16'], ", ") NameError: name 'string' is not defined From the context, I don't see string should be replaced by something else. Could you tell me why I have such an error? You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? -- Robin Koch -- https://mail.python.org/mailman/listinfo/python-list
Re: Does Python 2.7 do Open Office
On Thu, 03 Dec 2015 01:54:16 +0100, Laura Creighton wrote: >In a message of Wed, 02 Dec 2015 18:50:34 -0500, Seymore4Head writes: >>I have a text file I would like to search through but I have tried it >>before. I don't remember why they are not compatible together, but I >>wanted to ask to make sure. >> >>I know I can convert the file to plain text but it would be nice not >>to have to do that. >> >>-- >>https://mail.python.org/mailman/listinfo/python-list > >You are looking for PyUNO.Unfortuntately it is not well >documented, but I have heard good things about this as documentation. >https://documenthacker.wordpress.com/2013/03/05/first-draft-released/ > >Laura Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
Adam Funk wrote: > On 2015-12-03, Adam Funk wrote: > >> I'm having trouble with some input files that are almost all proper >> UTF-8 but with a couple of troublesome characters mixed in, which I'd >> like to ignore instead of throwing ValueError. I've found the >> openhook for the encoding >> >> for line in fileinput.input(options.files, >> openhook=fileinput.hook_encoded("utf-8")): >> do_stuff(line) >> >> which the documentation describes as "a hook which opens each file >> with codecs.open(), using the given encoding to read the file", but >> I'd like codecs.open() to also have the errors='ignore' or >> errors='replace' effect. Is it possible to do this? > > I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different > machines). Have a look at the source of fileinput.hook_encoded: def hook_encoded(encoding): import io def openhook(filename, mode): mode = mode.replace('U', '').replace('b', '') or 'r' return io.open(filename, mode, encoding=encoding, newline='') return openhook You can use it as a template to write your own factory function: def my_hook_encoded(encoding, errors=None): import io def openhook(filename, mode): mode = mode.replace('U', '').replace('b', '') or 'r' return io.open( filename, mode, encoding=encoding, newline='', errors=errors) return openhook for line in fileinput.input( options.files, openhook=my_hook_encoded("utf-8", errors="ignore")): do_stuff(line) Another option is to create the function on the fly: for line in fileinput.input( options.files, openhook=functools.partial( io.open, encoding="utf-8", errors="replace")): do_stuff(line) (codecs.open() instead of io.open() should also work) -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 2015-12-03 15:12, Adam Funk wrote: I'm having trouble with some input files that are almost all proper UTF-8 but with a couple of troublesome characters mixed in, which I'd like to ignore instead of throwing ValueError. I've found the openhook for the encoding for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): do_stuff(line) which the documentation describes as "a hook which opens each file with codecs.open(), using the given encoding to read the file", but I'd like codecs.open() to also have the errors='ignore' or errors='replace' effect. Is it possible to do this? It looks like it's not possible with the standard "hook_encoded", but you could write your own alternative: import codecs def my_hook_encoded(encoding, errors): def opener(path, mode): return codecs.open(path, mode, encoding=encoding, errors=errors) return opener for line in fileinput.input(options.files, openhook=fileinput.my_hook_encoded("utf-8", "ignore")): do_stuff(line) -- https://mail.python.org/mailman/listinfo/python-list
Re: filter a list of strings
On 12/3/2015 7:28 AM, Mark Lawrence wrote: On 03/12/2015 01:15, c.bu...@posteo.jp wrote: I would like to know how this could be done more elegant/pythonic. I have a big list (over 10.000 items) with strings (each 100 to 300 chars long) and want to filter them. list = . for item in list[:]: if 'Banana' in item: list.remove(item) if 'Car' in item: list.remove(item) There are a lot of more conditions of course. This is just example code. It doesn't look nice to me. To much redundance. targets = ['Banana', 'Car'...] for item in list[:]: for target in targets: if target in item: list.remove(item) btw: Is it correct to iterate over a copy (list[:]) of that string list and not the original one? Absolutely :) Even better, instead of copying and deleting, which is O(k*n), where n is the len of list and k is number deletions, is to create a new list with the item you want. In other words, actually filter, as you said you want. targets = {'Banana', 'Car', ...} # set intentional newlist = [item for item in oldlist if item not in targets] Generically, replace 'not in targets' with any boolean expression or function. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On 2015-12-03 16:00, Robin Koch wrote: Am 03.12.2015 um 10:02 schrieb Gary Herron: On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- My Python console is 2.7. It should be no problem because I see the tutorial is 2.7 too. The console has these display: string.join(['1', '2', '4', '8', '16'], ", ") --- NameError Traceback (most recent call last) in () > 1 string.join(['1', '2', '4', '8', '16'], ", ") NameError: name 'string' is not defined From the context, I don't see string should be replaced by something else. Could you tell me why I have such an error? You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? The documentation says: """The string module contains a number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings.""" The "join" function is one of those old functions you don't need any more, and you're correct that the the "join" method should be used instead. -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: > Now *I* am confused. > > Shouldn't it be > > ", ".join(['1', '2', '4', '8', '16']) > > instead? Without any importing? That would be the normal way to write it. The FAQ entry is suggesting the string module function as an alternative for those who can't accept it as a string method. -- https://mail.python.org/mailman/listinfo/python-list
urllib2.urlopen() crashes on Windows 2008 Server
I have a Python2 program which runs fine on Windows 7, but crashes on Windows 2008 Server R2 64 bit: downloading http://fex.belwue.de/download/7za.exe Traceback (most recent call last): File "", line 1992, in File "", line 180, in main File "", line 329, in get_ID File "", line 1627, in check_7z File "C:\Software\Python\lib\urllib2.py", line 154, in urlopen File "C:\Software\Python\lib\urllib2.py", line 431, in open File "C:\Software\Python\lib\urllib2.py", line 449, in _open File "C:\Software\Python\lib\urllib2.py", line 409, in _call_chain File "C:\Software\Python\lib\urllib2.py", line 1227, in http_open File "C:\Software\Python\lib\urllib2.py", line 1200, in do_open File "C:\Software\Python\lib\httplib.py", line 1132, in getresponse File "C:\Software\Python\lib\httplib.py", line 485, in begin File "C:\Software\Python\lib\mimetools.py", line 25, in __init__ File "C:\Software\Python\lib\rfc822.py", line 108, in __init__ File "C:\Software\Python\lib\httplib.py", line 319, in readheaders File "C:\Software\Python\lib\socket.py", line 480, in readline error: [Errno 10054] Eine vorhandene Verbindung wurde vom Remotehost geschlossen This is the function where the error happens: if python2: import urllib2 as urllib if python3: import urllib.request as urllib def check_7z(): global sz sz = path.join(fexhome,'7za.exe') szurl = "http://fex.belwue.de/download/7za.exe"; if not path.exists(sz) or path.getsize(sz) < : try: szo = open(sz,'wb') except (IOError,OSError) as e: die('cannot write %s - %s' % (sz,e.strerror)) printf("\ndownloading %s\n",szurl) try: req = urllib.Request(szurl) req.add_header('User-Agent',useragent) u = urllib.urlopen(req) # line 1627 # except urllib.URLError as e: die('cannot get %s - %s' % (szurl,e.reason)) except urllib.HTTPError as e: die('cannot get %s - server reply: %d %s' % (szurl,e.code,e.reason)) if u.getcode() == 200: copy_file_obj(u,szo) szo.close() else: die('cannot get %s - server reply: %d' % (szurl,u.getcode())) The curious thing is: the download was successful, the file 7za.exe is there in the local directory! -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de Universitaet Stuttgart Tel:++49-711-68565868 Allmandring 30aFax:++49-711-682357 70550 Stuttgart (Germany) WWW:http://www.tik.uni-stuttgart.de/ -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
In a message of Thu, 03 Dec 2015 15:12:15 +, Adam Funk writes: >I'm having trouble with some input files that are almost all proper >UTF-8 but with a couple of troublesome characters mixed in, which I'd >like to ignore instead of throwing ValueError. I've found the >openhook for the encoding > >for line in fileinput.input(options.files, >openhook=fileinput.hook_encoded("utf-8")): >do_stuff(line) > >which the documentation describes as "a hook which opens each file >with codecs.open(), using the given encoding to read the file", but >I'd like codecs.open() to also have the errors='ignore' or >errors='replace' effect. Is it possible to do this? > >Thanks. This should be both easy to add, and useful, and I happen to know that fileinput is being hacked on by Serhiy Storchaka right now, who agrees that this would be easy. So, with his approval, I stuck this into the tracker. http://bugs.python.org/issue25788 Future Pythons may not have the problem. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 12/3/2015 10:18 AM, Adam Funk wrote: On 2015-12-03, Adam Funk wrote: I'm having trouble with some input files that are almost all proper UTF-8 but with a couple of troublesome characters mixed in, which I'd like to ignore instead of throwing ValueError. I've found the openhook for the encoding for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): do_stuff(line) which the documentation describes as "a hook which opens each file with codecs.open(), using the given encoding to read the file", but I'd like codecs.open() to also have the errors='ignore' or errors='replace' effect. Is it possible to do this? I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different machines). fileinput is an ancient module that predates iterators (and generators) and context managers. Since by 2.7 open files are both context managers and line iterators, you can easily write your own multi-file line iteration that does exactly what you want. At minimum: for file in files: with codecs.open(file, errors='ignore') as f # did not look up signature, for line in f: do_stuff(line) To make this reusable, wrap in 'def filelines(files):' and replace 'do_stuff(line)' with 'yield line'. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
Am 03.12.2015 um 17:25 schrieb Ian Kelly: On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? That would be the normal way to write it. The FAQ entry is suggesting the string module function as an alternative for those who can't accept it as a string method. Whoops. Thanks and sorry. :-) -- Robin Koch -- https://mail.python.org/mailman/listinfo/python-list
Re: Are there any plans to support nCurses 6.0 with Python?
On Thursday, December 3, 2015 at 8:44:30 AM UTC-5, Mark Lawrence wrote: > On 03/12/2015 12:30, eclectic...@gmail.com wrote: > > The GNU Project has announced the release of nCurses 6.0. > > > > With it, Python curses would be able to support 256 colors instead of the > > current 8 or 16. > > > > I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is > > not usable by Python programs, such as my character-mode emulation of > > pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates > > a 71 color palette but will not work (its has been disabled) with the > > existing 16-color curses because text attributes (such as underline) > > partially overlay the foreground-background color-pair attributes. > > > > Work is all ready being done to support building Python with ncurses6, > see https://bugs.python.org/issue25720. Whether this alone meets your > needs or an enhancement request on the bug tracker against 3.6 is > required I'm really not qualified to say. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence ncurses6 provides both an application binary interface for ncurses6.0 an one for ncurses5.0. Perhaps it will take an enhancement request to adopt the ABI 6.0 that su[prts 256 colors. -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On 12/3/2015 11:00 AM, Robin Koch wrote: Am 03.12.2015 um 10:02 schrieb Gary Herron: On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- ... You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? Yes, that is what one *should* do in late 2.x and indeed must do in 3.x, where the string module has been stripped of the functions that later became string methods. The FAQ entry was written when the join method was new as a method and some people were upset by the reversal of the order of the two arguments, an iterable of strings and the joining string. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Does Python 2.7 do Open Office
On 12/3/2015 11:00 AM, Seymore4Head wrote: On Thu, 3 Dec 2015 00:47:42 +, MRAB wrote: On 2015-12-02 23:50, Seymore4Head wrote: I have a text file I would like to search through but I have tried it before. I don't remember why they are not compatible together, but I wanted to ask to make sure. I know I can convert the file to plain text but it would be nice not to have to do that. A quick search found this: https://wiki.openoffice.org/wiki/Python LibreOffice rather sensibly (given that it is a any-language unicode editor) jumped to 3.3 a couple of years ago. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On 03/12/2015 17:01, Robin Koch wrote: Am 03.12.2015 um 17:25 schrieb Ian Kelly: On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? That would be the normal way to write it. The FAQ entry is suggesting the string module function as an alternative for those who can't accept it as a string method. Whoops. Thanks and sorry. :-) You might like to note that here https://docs.python.org/3/faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method the reference to the string module function has been completely removed. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
Am 03.12.2015 um 18:42 schrieb Mark Lawrence: On 03/12/2015 17:01, Robin Koch wrote: Am 03.12.2015 um 17:25 schrieb Ian Kelly: On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? That would be the normal way to write it. The FAQ entry is suggesting the string module function as an alternative for those who can't accept it as a string method. Whoops. Thanks and sorry. :-) You might like to note that here https://docs.python.org/3/faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method the reference to the string module function has been completely removed. Actually I did. :-) I tried the line with my Python 3.4 and it didn't work. Then I sent my initial posting. After Ians answer I took a look in the 2.x and the 3.x FAQs and found exactly that phrase removed. :-) -- Robin Koch -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
Am 03.12.2015 um 18:23 schrieb Terry Reedy: On 12/3/2015 11:00 AM, Robin Koch wrote: Am 03.12.2015 um 10:02 schrieb Gary Herron: On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- ... You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? Yes, that is what one *should* do in late 2.x and indeed must do in 3.x, where the string module has been stripped of the functions that later became string methods. The FAQ entry was written when the join method was new as a method and some people were upset by the reversal of the order of the two arguments, an iterable of strings and the joining string. Thank you. I figured that out by now. :-) I just didn't followed the link of the OP. -- Robin Koch -- https://mail.python.org/mailman/listinfo/python-list
Idle, tk and MacOS
This in to webmaster. Somebody got an error message about their Tcl/Tk when they started using IDLE. They went to https://www.python.org/download/mac/tcltk/ and, yes indeed, their tk is 8.5.9, their OS is 10.8.5 so they have a problem. They downloaded the patch from ActiveState, and did _something_ which reported 'installation successful'. But when they restart Idle it still has 8.5.9 What else do they need to do? Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 2015-12-03, Peter Otten wrote: > def my_hook_encoded(encoding, errors=None): > import io > def openhook(filename, mode): > mode = mode.replace('U', '').replace('b', '') or 'r' > return io.open( > filename, mode, > encoding=encoding, newline='', > errors=errors) > return openhook > > for line in fileinput.input( > options.files, > openhook=my_hook_encoded("utf-8", errors="ignore")): > do_stuff(line) Perfect, thanks! > (codecs.open() instead of io.open() should also work) OK. -- The internet is quite simply a glorious place. Where else can you find bootlegged music and films, questionable women, deep seated xenophobia and amusing cats all together in the same place? --- Tom Belshaw -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 2015-12-03, Terry Reedy wrote: > fileinput is an ancient module that predates iterators (and generators) > and context managers. Since by 2.7 open files are both context managers > and line iterators, you can easily write your own multi-file line > iteration that does exactly what you want. At minimum: > > for file in files: > with codecs.open(file, errors='ignore') as f > # did not look up signature, > for line in f: > do_stuff(line) > > To make this reusable, wrap in 'def filelines(files):' and replace > 'do_stuff(line)' with 'yield line'. I like fileinput because if the file list is empty, it reads from stdin instead (so I can pipe something else's output into it). Unfortunately, the fix I got elsewhere in this thread doesn't seem to work for that! -- Science is what we understand well enough to explain to a computer. Art is everything else we do. --- Donald Knuth -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 2015-12-03, Laura Creighton wrote: > In a message of Thu, 03 Dec 2015 15:12:15 +, Adam Funk writes: >>I'm having trouble with some input files that are almost all proper >>UTF-8 but with a couple of troublesome characters mixed in, which I'd >>like to ignore instead of throwing ValueError. I've found the >>openhook for the encoding >> >>for line in fileinput.input(options.files, >>openhook=fileinput.hook_encoded("utf-8")): >>do_stuff(line) >> >>which the documentation describes as "a hook which opens each file >>with codecs.open(), using the given encoding to read the file", but >>I'd like codecs.open() to also have the errors='ignore' or >>errors='replace' effect. Is it possible to do this? >> >>Thanks. > > This should be both easy to add, and useful, and I happen to know that > fileinput is being hacked on by Serhiy Storchaka right now, who agrees > that this would be easy. So, with his approval, I stuck this into the > tracker. http://bugs.python.org/issue25788 > > Future Pythons may not have the problem. Good to know, thanks. -- You cannot really appreciate Dilbert unless you've read it in the original Klingon. --- Klingon Programmer's Guide -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
In a message of Thu, 03 Dec 2015 19:17:51 +, Adam Funk writes: >On 2015-12-03, Laura Creighton wrote: > >> In a message of Thu, 03 Dec 2015 15:12:15 +, Adam Funk writes: >>>I'm having trouble with some input files that are almost all proper >>>UTF-8 but with a couple of troublesome characters mixed in, which I'd >>>like to ignore instead of throwing ValueError. I've found the >>>openhook for the encoding >>> >>>for line in fileinput.input(options.files, >>>openhook=fileinput.hook_encoded("utf-8")): >>>do_stuff(line) >>> >>>which the documentation describes as "a hook which opens each file >>>with codecs.open(), using the given encoding to read the file", but >>>I'd like codecs.open() to also have the errors='ignore' or >>>errors='replace' effect. Is it possible to do this? >>> >>>Thanks. >> >> This should be both easy to add, and useful, and I happen to know that >> fileinput is being hacked on by Serhiy Storchaka right now, who agrees >> that this would be easy. So, with his approval, I stuck this into the >> tracker. http://bugs.python.org/issue25788 >> >> Future Pythons may not have the problem. > >Good to know, thanks. Well, we have moved right along to 'You write the patch, Laura' so I can pretty much guarantee that future Pythons won't have the problem. :) Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Idle, tk and MacOS
In a message of Thu, 03 Dec 2015 20:34:10 +0100, Laura Creighton writes: >This in to webmaster. Somebody got an error message about their >Tcl/Tk when they started using IDLE. > >They went to https://www.python.org/download/mac/tcltk/ >and, yes indeed, their tk is 8.5.9, their OS is 10.8.5 so they >have a problem. They downloaded the patch from ActiveState, >and did _something_ which reported 'installation successful'. > >But when they restart Idle it still has 8.5.9 > >What else do they need to do? > >Laura The OP reported that trying to do it again seems to have worked great, so I guess something went wrong the first time. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: getting fileinput to do errors='ignore' or 'replace'?
On 3 Dec 2015 16:50, "Terry Reedy" wrote: > > On 12/3/2015 10:18 AM, Adam Funk wrote: >> >> On 2015-12-03, Adam Funk wrote: >> >>> I'm having trouble with some input files that are almost all proper >>> UTF-8 but with a couple of troublesome characters mixed in, which I'd >>> like to ignore instead of throwing ValueError. I've found the >>> openhook for the encoding >>> >>> for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): >>> do_stuff(line) >>> >>> which the documentation describes as "a hook which opens each file >>> with codecs.open(), using the given encoding to read the file", but >>> I'd like codecs.open() to also have the errors='ignore' or >>> errors='replace' effect. Is it possible to do this? >> >> >> I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different >> machines). > > > fileinput is an ancient module that predates iterators (and generators) and context managers. Since by 2.7 open files are both context managers and line iterators, you can easily write your own multi-file line iteration that does exactly what you want. At minimum: > > for file in files: > with codecs.open(file, errors='ignore') as f > # did not look up signature, > for line in f: > do_stuff(line) The above is fine but... > To make this reusable, wrap in 'def filelines(files):' and replace 'do_stuff(line)' with 'yield line'. That doesn't work entirely correctly as you end up yielding from inside a with statement. If the user of your generator function doesn't fully consume the generator then whichever file is currently open is not guaranteed to be closed. -- Oscar -- https://mail.python.org/mailman/listinfo/python-list
Is there a way to set several list elements a same value with one line code
Hi, I remember that there is a way to set several list elements a same value with one line code. Excuse me, I don't remember the accurate syntax on the code snippet. But the basic format looks like this. 1. There is a four-element list, such as: bb=[[[]],[[]],[[]],[[]]] 2. An assignment line is here: bb[0]='a' 3. Then, all 4 element of bb is set with the above value. bb=[['a'],['a'],['a'],['a']] The above three line codes are what I guess (I forgot the original tutorial now). Do you remember there is such a list application? Thanks, -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to set several list elements a same value with one line code
On 2015-12-04 00:30, Robert wrote: Hi, I remember that there is a way to set several list elements a same value with one line code. Excuse me, I don't remember the accurate syntax on the code snippet. But the basic format looks like this. 1. There is a four-element list, such as: bb=[[[]],[[]],[[]],[[]]] 2. An assignment line is here: bb[0]='a' 3. Then, all 4 element of bb is set with the above value. bb=[['a'],['a'],['a'],['a']] The above three line codes are what I guess (I forgot the original tutorial now). Do you remember there is such a list application? Do you mean this behaviour: bb=[[[]]] * 4 print(bb) [[[]], [[]], [[]], [[]]] bb[0][0]='a' print(bb) [['a'], ['a'], ['a'], ['a']] ? That's because the bb contains 4 references to the same list. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to set several list elements a same value with one line code
On Thursday, December 3, 2015 at 7:59:16 PM UTC-5, MRAB wrote: > On 2015-12-04 00:30, Robert wrote: > > Hi, > > > > I remember that there is a way to set several list elements a same value > > with > > one line code. Excuse me, I don't remember the accurate syntax on the code > > snippet. But the basic format looks like this. > > > > 1. There is a four-element list, such as: > > bb=[[[]],[[]],[[]],[[]]] > > 2. An assignment line is here: > > bb[0]='a' > > 3. Then, all 4 element of bb is set with the above value. > > bb=[['a'],['a'],['a'],['a']] > > > > The above three line codes are what I guess (I forgot the original tutorial > > now). Do you remember there is such a list application? > > > Do you mean this behaviour: > > >>> bb=[[[]]] * 4 > >>> print(bb) > [[[]], [[]], [[]], [[]]] > >>> bb[0][0]='a' > >>> print(bb) > [['a'], ['a'], ['a'], ['a']] > > ? > > That's because the bb contains 4 references to the same list. Yes! What you post is I want. Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is Microsoft Windows secretly downloading childporn to your computer ?!
On Thu, 3 Dec 2015 09:16:32 + (UTC), Juha Nieminen wrote: >In comp.lang.c++ Chris in Makati wrote: >> On Wed, 2 Dec 2015 08:57:44 + (UTC), Juha Nieminen >> wrote: >> >>>In comp.lang.c++ Steve Hayes wrote: You download things FROM a computer, you upload them TO a computer. >>> >>>It's a matter of perspective. If a hacker breaks into your computer and >>>starts a download from somewhere else into your computer, isn't the hacker >>>"downloading" things to your computer? >> >> Does it matter? As far as the law is concerned, it is possession of >> child porn that's illegal. How it got there is irrelevant. > >Most judiciary systems are not robots following a narrow set of instructions. >If they determine that it wasn't your fault, they will not punish the >innocent. > >Besides, how would they even know what's in your computer? If you do a Google search for you will find literally thousands of cases where raids have taken place and people have been found with this material on their computers. In many of these cases the authorities have traced the IP addresses of people whose computers have made connections to known sites that host child porn. It's no use trying to claim that a bot you weren't aware of downloaded it without your knowledge. If you could get off the hook that easily everybody who was interested in the stuff would deliberately install such a bot and use that as an excuse. -- https://mail.python.org/mailman/listinfo/python-list
Re: HELP PLEASE printing single characters!
On 12/02/2015 04:08 PM, John Strick wrote: On Wednesday, December 2, 2015 at 12:58:30 PM UTC-6, Dylan Riley wrote: hi all, I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. my code is: #Create a program that prints a list of words in random order. #The program should print all the words and not repeat any. import random LIST = ["blue ", "red ", "yellow ", "green ", "orange "] order = [] print("This game will print a random order of colours") print("The list is", LIST) input("press enter to start") while LIST != []: choice = random.choice(LIST) order += choice while choice in LIST: LIST.remove(choice) print(order) input("press enter to exit") thanks in advance guys You could just shuffle the list first, then loop through it. This will guarantee that each color is only used once. Not quite. Only if the original list has no repetitions. My personal approach would be to use a set to eliminate the duplicates, convert back to a list and shuffle that. no_reps = list(set(LIST)) random.shuffle(no_reps) print(no_reps) # Or use loop to print one-per-line -=- Larry -=- -- https://mail.python.org/mailman/listinfo/python-list
How to bounce the ball forever around the screen
from Tkinter import * window = Tk() canvas = Canvas(window, width=500, height=500, background="green") canvas.pack() def move_ball(speed_x, speed_y): box = canvas.bbox("ball") x1 = box[0] y1 = box[1] x2 = box[2] y2 = box[3] if x1 <= 0: speed_x = 0 speed_y = 0 canvas.move("ball", speed_x, speed_y) canvas.after(30, move_ball, speed_x, speed_y) canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball") move_ball(-10, 7) mainloop() where in the code should i change to make the ball bounce around forever. is it the x and y? -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to set several list elements a same value with one line code
On Thu, 03 Dec 2015 16:30:25 -0800, Robert wrote: > Hi, > > I remember that there is a way to set several list elements a same value > with > one line code. Excuse me, I don't remember the accurate syntax on the > code snippet. But the basic format looks like this. > > 1. There is a four-element list, such as: >bb=[[[]],[[]],[[]],[[]]] > 2. An assignment line is here: >bb[0]='a' > 3. Then, all 4 element of bb is set with the above value. >bb=[['a'],['a'],['a'],['a']] > > The above three line codes are what I guess (I forgot the original > tutorial > now). Do you remember there is such a list application? bb = [ for i in range()] will create bb as a list of size whatever elements each of which is eg: >>> bb = [ ['a'] for i in range(4)] >>> bb [['a'], ['a'], ['a'], ['a']] >>> bb = [ 0 for i in range(5)] >>> bb [0, 0, 0, 0, 0] >>> -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list