3 ms·
I do that all the time in the interpreter, especially when slicing pandas DataFrame objects, e.g.: df_subset = df['date buyer nwidgets'.split()] That is f
by oddthink 12y ago
I do that all the time in the interpreter, especially when slicing pandas DataFrame objects, e.g.:
df_subset = df['date buyer nwidgets'.split()]
That is far easier to type than the explicit list, with all its punctuation. Now, it's definitely weird that they did a `split(" ")` rather than just using the default, but the idea is the same.
I do try to strip stuff like that out before I put it into a script, replacing it with the explicit list, but I'm never sure if that actually improves anything. It's not as if the explicit list is any easier to read.
- klibertp 12y agoIt's not weird, it's wrong: In [1]: "a string r".split(" ") Out[1]: ['a', '', '', '', 'string', '', '', '', '', 'r'] In [2]: "a string r".split() Out[2]: ['a', 'string', 'r']
- glomph 12y agoIn their case though that wouldn't have been a problem as each word was split on a single space.
- hcarvalhoalves 12y agoSplit without argument is equivalent to: >>> filter(None, " quick hack for split".split(" ")) ['quick', 'hack', 'for', 'split']
- klibertp 12y agoYeah, or re.split(r'\s+', ...), or something - the issue here is that you need to know about this. From the comment a few levels up I understood that the code which used the str.split with " " argument didn't signify that someone who written it knew about its semantics. If he did and it was really what was intended then ofc it's completely ok, but if not, it can easily lead to bugs. For example, if the user is required to input several ints separated with whitespace, this: map(int, input_str.split()) will rise only in expected cases, while this: map(int, input_str.split(" ")) can lead to rejecting correct input just because someone pressed space twice. It's very frustrating for the user, too, because whitespace are hard to spot visually. So, I don't know if this qualifies as antipattern, but I think if I saw .split(" ") instead of .split() in the code I'd at the very least expect the comment explaining why it's used.
- blossoms 12y agoI don't mean to be pedantic, but a list (I am assuming df is a list) requires an int. (That sentence I wrote about using hashable types need not apply, sorry!) If you ran that code, you would get this error: TypeError: list indices must be integers, not list
- gipp 12y agoThat's a pandas dataframe (idiomatically denoted df), not a list. It has funky slicing properties, and he's selecting columns of the dataframe in a perfectly valid way.