title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Regular Expression Matching First Non-Repeated Character | 39,796,852 | 27 | 2016-09-30T17:22:24Z | 39,796,953 | 14 | 2016-09-30T17:29:38Z | [
"python",
"regex",
"regex-lookarounds"
] | **TL;DR**
`re.search("(.)(?!.*\1)", text).group()` doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return ... | Well let's take your `tooth` example - here is what the regex-engine does (a lot simplified for better understanding)
Start with `t` then look ahead in the string - and fail the lookahead, as there is another `t`.
```
tooth
^ °
```
Next take `o`, look ahead in the string - and fail, as there is another `o`.
```
t... |
Regular Expression Matching First Non-Repeated Character | 39,796,852 | 27 | 2016-09-30T17:22:24Z | 39,890,983 | 11 | 2016-10-06T08:19:28Z | [
"python",
"regex",
"regex-lookarounds"
] | **TL;DR**
`re.search("(.)(?!.*\1)", text).group()` doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return ... | [Sebastian's answer](http://stackoverflow.com/a/39796953/3764814) already explains pretty well why your current attempt doesn't work.
### .NET
Since ~~you're~~ [revo](http://stackoverflow.com/users/1020526/revo) is interested in a .NET flavor workaround, the solution becomes trivial:
```
(?<letter>.)(?!.*?\k<letter>... |
cryptography AssertionError: sorry, but this version only supports 100 named groups | 39,829,473 | 13 | 2016-10-03T10:28:14Z | 39,830,224 | 22 | 2016-10-03T11:11:24Z | [
"python",
"python-2.7",
"travis-ci",
"python-cryptography"
] | I'm installing several python packages via `pip install` on travis,
```
language: python
python:
- '2.7'
install:
- pip install -r requirements/env.txt
```
Everything worked fine, but today I started getting following error:
```
Running setup.py install for cryptography
Traceback (most recent call last):
File "<s... | There is a bug with PyCParser - See <https://github.com/pyca/cryptography/issues/3187>
The work around is to use another version or to not use the binary distribution.
```
pip install git+https://github.com/eliben/pycparser@release_v2.14
```
or
```
pip install --no-binary pycparser
``` |
Getting previous index values of a python list items after shuffling | 39,832,773 | 3 | 2016-10-03T13:25:10Z | 39,832,854 | 12 | 2016-10-03T13:28:48Z | [
"python"
] | Let's say I have such a python list:
```
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
by using `random.shuffle`,
```
>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
```
I am having the above list.
How can I get the previous index values list of each item in the shuffled list? | You could pair each item with its index using `enumerate`, then shuffle that.
```
>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>>> indices
(0, 1, 2, 4, 5, 3)
```
One advantage of this approach is that it works r... |
How does one add an item to GTK's "recently used" file list from Python? | 39,836,725 | 12 | 2016-10-03T17:00:54Z | 39,927,261 | 10 | 2016-10-07T23:53:51Z | [
"python",
"gtk",
"pygtk",
"gtk3"
] | I'm trying to add to the "recently used" files list from Python 3 on Ubuntu.
I am able to successfully *read* the recently used file list like this:
```
from gi.repository import Gtk
recent_mgr = Gtk.RecentManager.get_default()
for item in recent_mgr.get_items():
print(item.get_uri())
```
This prints out the sam... | A `Gtk.RecentManager` needs to emit the `changed` signal for the update to be written in a private attribute of the C++ class. To use a `RecentManager` object in an application, you need to start the event loop by calling `Gtk.main`:
```
from gi.repository import Gtk
recent_mgr = Gtk.RecentManager.get_default()
uri =... |
How to make an integer larger than any other integer? | 39,843,488 | 41 | 2016-10-04T03:00:56Z | 39,843,523 | 61 | 2016-10-04T03:04:16Z | [
"python",
"python-3.x"
] | Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in [@Jason Orendorff answer below](http://stackoverflow.com/a/39856605/336527).
... | Since python integers are unbounded, you have to do this with a custom class:
```
import functools
@functools.total_ordering
class NeverSmaller(object):
def __le__(self, other):
return False
class ReallyMaxInt(NeverSmaller, int):
def __repr__(self):
return 'ReallyMaxInt()'
```
Here I've used... |
How to make an integer larger than any other integer? | 39,843,488 | 41 | 2016-10-04T03:00:56Z | 39,855,605 | 23 | 2016-10-04T14:57:45Z | [
"python",
"python-3.x"
] | Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in [@Jason Orendorff answer below](http://stackoverflow.com/a/39856605/336527).
... | Konsta Vesterinen's [`infinity.Infinity`](https://github.com/kvesteri/infinity) would work ([pypi](https://pypi.python.org/pypi/infinity/)), except that it doesn't inherit from `int`, but you can subclass it:
```
from infinity import Infinity
class IntInfinity(Infinity, int):
pass
assert isinstance(IntInfinity(), ... |
How to make an integer larger than any other integer? | 39,843,488 | 41 | 2016-10-04T03:00:56Z | 39,856,605 | 15 | 2016-10-04T15:45:43Z | [
"python",
"python-3.x"
] | Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in [@Jason Orendorff answer below](http://stackoverflow.com/a/39856605/336527).
... | > Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.
This sounds like a flaw in the library that should be fixed in its interface. Then all its users would benefit. What library is it?
Creating a magical int subclass with overridden compar... |
Is python tuple assignment order fixed? | 39,855,410 | 2 | 2016-10-04T14:49:58Z | 39,855,637 | 7 | 2016-10-04T14:58:56Z | [
"python",
"tuples",
"variable-assignment"
] | Will
```
a, a = 2, 1
```
always result in a equal to 1? In other words, is tuple assignment guaranteed to be left-to-right?
The matter becomes relevant when we don't have just a, but a[i], a[j] and i and j may or may not be equal. | Yes, it is part of the python language reference that tuple assignment must take place left to right.
<https://docs.python.org/2.3/ref/assignment.html>
> An assignment statement evaluates the expression list (remember that
> this can be a single expression or a comma-separated list, the latter
> yielding a tuple) and... |
Can a python function know when it's being called by a list comprehension? | 39,887,880 | 3 | 2016-10-06T05:04:10Z | 39,888,195 | 8 | 2016-10-06T05:30:50Z | [
"python"
] | I want to make a python function that behaves differently when it's being called from a list comprehension:
```
def f():
# this function returns False when called normally,
# and True when called from a list comprehension
pass
>>> f()
False
>>> [f() for _ in range(3)]
[True, True, True]
```
I tried looki... | You can determine this by inspecting the stack frame in the following sort of way:
```
def f():
try:
raise ValueError
except Exception as e:
if e.__traceback__.tb_frame.f_back.f_code.co_name == '<listcomp>':
return True
```
Then:
```
>>> print(f())
None
>>> print([f() for x in ran... |
Is there a more Pythonic way to combine an Else: statement and an Except:? | 39,903,242 | 32 | 2016-10-06T18:29:51Z | 39,903,338 | 9 | 2016-10-06T18:34:43Z | [
"python",
"python-2.7"
] | I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. `"overall_weight"` in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the `"over... | Use `.get()` with a default argument of `"N/A"` which will be used if the key does not exist:
```
nObject.TextString = self.var.jobDetails.get("Overall Weight", "N/A")
```
# Update
If empty strings need to be handled, simply modify as follows:
```
nObject.TextString = self.var.jobDetails.get("Overall Weight") or "N... |
Is there a more Pythonic way to combine an Else: statement and an Except:? | 39,903,242 | 32 | 2016-10-06T18:29:51Z | 39,903,350 | 16 | 2016-10-06T18:35:11Z | [
"python",
"python-2.7"
] | I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. `"overall_weight"` in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the `"over... | Use `get()` function for dictionaries. It will return `None` if the key doesn't exist or if you specify a second value, it will set that as the default. Then your syntax will look like:
```
nObject.TextString = self.var.jobDetails.get('Overall Weight', 'N/A')
``` |
Is there a more Pythonic way to combine an Else: statement and an Except:? | 39,903,242 | 32 | 2016-10-06T18:29:51Z | 39,903,519 | 63 | 2016-10-06T18:45:36Z | [
"python",
"python-2.7"
] | I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. `"overall_weight"` in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the `"over... | Use `dict.get()` which will return the value associated with the given key if it exists otherwise `None`. (Note that `''` and `None` are both falsey values.) If `s` is true then assign it to `nObject.TextString` otherwise give it a value of `"N/A"`.
```
if nObject.TextString == "overall_weight":
nObject.TextString... |
Is there a way to compile python application into static binary? | 39,913,847 | 22 | 2016-10-07T09:24:20Z | 40,057,634 | 11 | 2016-10-15T10:00:42Z | [
"python",
"build"
] | What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.
Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manual... | There are two ways you could go about to solve your problem
1. Use a static builder, like freeze, or pyinstaller, or py2exe
2. Compile using cython
I will explain how you can go about doing it using the second, since the first method is not cross platform and version, and has been explained in other answers. Also, us... |
Understanding variable types, names and assignment | 39,917,988 | 3 | 2016-10-07T13:02:58Z | 39,918,038 | 7 | 2016-10-07T13:06:02Z | [
"python"
] | In Python, if you want to define a variable, you don't have to specify the type of it, unlike other languages such as C and Java.
So how can the Python interpreter distinguish between variables and give it the required space in memory like `int` or `float`? | In Python all values are objects with built-in type info. Variables are references to these values. So their type is 'dynamic', just equal to the type of what they happen to refer to (point to) at a particular moment.
Whenever memory is allocated for the contents of a variable, a value is available. Since it has a typ... |
Mapping Python list values to dictionary values | 39,955,222 | 2 | 2016-10-10T09:28:49Z | 39,955,362 | 7 | 2016-10-10T09:36:56Z | [
"python"
] | I have a list of rows...
`rows = [2, 21]`
And a dictionary of data...
`data = {'x': [46, 35], 'y': [20, 30]}`
I'd like to construct a second dictionary, `dataRows`, keyed by the row that looks like this...
`dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}`
I tried the following code, but the values of `... | Your issue is that you are not puting sub-dictionaries inside dataRows. The fix would be this:
```
for i, row in enumerate(rows):
dataRows[row] = {}
for key, value in data.items():
dataRows[row][key] = value[i]
``` |
What are variable annotations in Python 3.6? | 39,971,929 | 15 | 2016-10-11T07:00:15Z | 39,972,031 | 15 | 2016-10-11T07:08:33Z | [
"python",
"python-3.x",
"annotations",
"type-hinting",
"python-3.6"
] | Python 3.6 is about to be released. [PEP 494 -- Python 3.6 Release Schedule](https://www.python.org/dev/peps/pep-0494/) mentions the end of December, so I went through [What's New in Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html) to see they mention the *variable annotations*:
> [PEP 484](https://www.pytho... | Everything between `:` and the `=` is a type hint, so `primes` is indeed defined as `List[int]`, and initially set to an empty list (and `stats` is an empty dictionary initially, defined as `Dict[str, int]`).
`List[int]` and `Dict[str, int]` are not part of the next syntax however, these were already defined in the Py... |
What are variable annotations in Python 3.6? | 39,971,929 | 15 | 2016-10-11T07:00:15Z | 39,973,133 | 11 | 2016-10-11T08:21:24Z | [
"python",
"python-3.x",
"annotations",
"type-hinting",
"python-3.6"
] | Python 3.6 is about to be released. [PEP 494 -- Python 3.6 Release Schedule](https://www.python.org/dev/peps/pep-0494/) mentions the end of December, so I went through [What's New in Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html) to see they mention the *variable annotations*:
> [PEP 484](https://www.pytho... | Indeed, variable annotations are just the next step from `# type` comments as they where defined in `PEP 484`; the rationale behind this change is highlighted in the [respective PEP section](https://www.python.org/dev/peps/pep-0526/#rationale). So, instead of hinting the type with:
```
primes = [] # type: List[int]
`... |
Dictionaries are ordered in Python 3.6 | 39,980,323 | 72 | 2016-10-11T14:59:23Z | 39,980,548 | 27 | 2016-10-11T15:09:00Z | [
"python",
"python-3.x",
"dictionary",
"python-internals",
"python-3.6"
] | Dictionaries are ordered in Python 3.6, unlike in previous Python incarnations. This seems like a substantial change, but it's only a short paragraph in the [documentation](https://docs.python.org/3.6/whatsnew/3.6.html#other-language-changes). It is described as an implementation detail rather than a language feature, ... | Below is answering the original first question:
> Should I use `dict` or `OrderedDict` in Python 3.6?
I think this sentence from the documentation is actually enough to answer your question
> The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon
... |
Dictionaries are ordered in Python 3.6 | 39,980,323 | 72 | 2016-10-11T14:59:23Z | 39,980,744 | 57 | 2016-10-11T15:17:53Z | [
"python",
"python-3.x",
"dictionary",
"python-internals",
"python-3.6"
] | Dictionaries are ordered in Python 3.6, unlike in previous Python incarnations. This seems like a substantial change, but it's only a short paragraph in the [documentation](https://docs.python.org/3.6/whatsnew/3.6.html#other-language-changes). It is described as an implementation detail rather than a language feature, ... | > How does the Python 3.6 dictionary implementation perform better than the older one while preserving element order?
Essentially by keeping two arrays, one holding the entries for the dictionary in the order that they were inserted and the other holding a list of indices.
In the previous implementation a sparse arra... |
How to *not* create an instance | 39,988,779 | 2 | 2016-10-12T00:34:44Z | 39,988,807 | 7 | 2016-10-12T00:38:41Z | [
"python",
"python-3.x"
] | I would like to avoid the creation of an instance if the arguments do not match the expected values.
I.e. in short:
```
#!/usr/bin/env python3
class Test(object):
def __init__(self, reallydoit = True):
if reallydoit:
self.done = True
else:
return None
make_me = Test()
ma... | Just [raise](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) an exception in the [*\_\_init\_\_*](https://docs.python.org/3/reference/datamodel.html#object.__init__) method:
```
class Test(object):
def __init__(self, reallydoit = True):
if reallydoit:
self.done = True... |
Why does __slots__ = ('__dict__',) produce smaller instances? | 40,003,067 | 5 | 2016-10-12T15:55:31Z | 40,003,530 | 7 | 2016-10-12T16:18:18Z | [
"python",
"class",
"python-3.x"
] | ```
class Spam(object):
__slots__ = ('__dict__',)
```
Produces instances smaller than those of a "normal" class. Why is this?
Source: [David Beazley's recent tweet](https://twitter.com/dabeaz/status/785948782219231232). | To me, it looks like the memory savings come from the lack of a `__weakref__` on the instance.
So if we have:
```
class Spam1(object):
__slots__ = ('__dict__',)
class Spam2(object):
__slots__ = ('__dict__', '__weakref__')
class Spam3(object):
__slots__ = ('foo',)
class Eggs(object):
pass
objs = Sp... |
Why does map return a map object instead of a list in Python 3? | 40,015,439 | 20 | 2016-10-13T08:01:41Z | 40,015,480 | 7 | 2016-10-13T08:04:08Z | [
"python",
"python-3.x"
] | I am interested in understanding the [new language design of Python 3.x](http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x).
I do enjoy, in Python 2.7, the function `map`:
```
Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
```
However, in Python 3.x things ha... | Because it returns an iterator, it omit storing the full list in the memory. So that you can easily iterate over it in the future not making pain to memory. Possibly you even don't need a full list, but the part of it, until your condition is matched.
You can find this [docs](https://docs.python.org/3/glossary.html#te... |
list() uses more memory than list comprehension | 40,018,398 | 54 | 2016-10-13T10:25:25Z | 40,018,719 | 41 | 2016-10-13T10:40:13Z | [
"python",
"list",
"list-comprehension"
] | So i was playing with `list` objects and found little strange thing that if `list` is created with `list()` it uses more memory, than list comprehension? I'm using Python 3.5.2
```
In [1]: import sys
In [2]: a = list(range(100))
In [3]: sys.getsizeof(a)
Out[3]: 1008
In [4]: b = [i for i in range(100)]
In [5]: sys.gets... | I think you're seeing over-allocation patterns this is a [sample from the source](https://github.com/python/cpython/blob/3.5/Objects/listobject.c#L42):
```
/* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amor... |
list() uses more memory than list comprehension | 40,018,398 | 54 | 2016-10-13T10:25:25Z | 40,019,900 | 23 | 2016-10-13T11:37:10Z | [
"python",
"list",
"list-comprehension"
] | So i was playing with `list` objects and found little strange thing that if `list` is created with `list()` it uses more memory, than list comprehension? I'm using Python 3.5.2
```
In [1]: import sys
In [2]: a = list(range(100))
In [3]: sys.getsizeof(a)
Out[3]: 1008
In [4]: b = [i for i in range(100)]
In [5]: sys.gets... | Thanks everyone for helping me to understand that awesome Python.
I don't want to make question that massive(that why i'm posting answer), just want to show and share my thoughts.
As @ReutSharabani noted correctly: "list() deterministically determines list size". You can see it from that graph.
[ clearly describes how the metaclass of a class is determined:
> * if no bases and no explicit metaclass are given, then type() is used
> * if an explicit metaclass is given and it is ... | Regarding your first question the metaclass should be `MyMetaclass` (which it's so):
```
In [7]: print(type(MyClass), type(MyDerived))
<class '__main__.MyMetaclass'> <class '__main__.MyMetaclass'>
```
The reason is that if the metaclass is not an instance of type python calls the methaclass by passing these arguments... |
Removing elements from an array that are in another array | 40,055,835 | 11 | 2016-10-15T06:36:16Z | 40,056,135 | 9 | 2016-10-15T07:07:33Z | [
"python",
"arrays",
"numpy"
] | Say I have these 2D arrays A and B.
How can I remove elements from A that are in B.
```
A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]])
B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]])
#output = [[1,1,2], [1,1,3]]
```
---
To be more precise, I would like to do something like this.
`... | Here is a Numpythonic approach with *broadcasting*:
```
In [83]: A[np.all(np.any((A-B[:, None]), axis=2), axis=0)]
Out[83]:
array([[1, 1, 2],
[1, 1, 3]])
```
Here is a timeit with other answer:
```
In [90]: def cal_diff(A, B):
....: A_rows = A.view([('', A.dtype)] * A.shape[1])
....: B_rows = B... |
Removing elements from an array that are in another array | 40,055,835 | 11 | 2016-10-15T06:36:16Z | 40,056,251 | 9 | 2016-10-15T07:19:03Z | [
"python",
"arrays",
"numpy"
] | Say I have these 2D arrays A and B.
How can I remove elements from A that are in B.
```
A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]])
B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]])
#output = [[1,1,2], [1,1,3]]
```
---
To be more precise, I would like to do something like this.
`... | Based on [`this solution`](http://stackoverflow.com/a/38674038/3293881) to [`Find the row indexes of several values in a numpy array`](http://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array), here's a NumPy based solution with less memory footprint and could be beneficial wh... |
Why can yield be indexed? | 40,061,280 | 6 | 2016-10-15T16:06:41Z | 40,061,337 | 12 | 2016-10-15T16:11:49Z | [
"python",
"python-2.7",
"indexing",
"generator",
"yield"
] | I thought I could make my python (2.7.10) code simpler by directly accessing the index of a value passed to a generator via `send`, and was surprised the code ran. I then discovered an index applied to `yield` doesn't really do anything, nor does it throw an exception:
```
def gen1():
t = yield[0]
assert t
... | You are not indexing. You are yielding a list; the expression `yield[0]` is really just the same as the following (but without a variable):
```
lst = [0]
yield lst
```
If you look at what `next()` returned you'd have gotten that list:
```
>>> def gen1():
... t = yield[0]
... assert t
... yield False
...
>>> g ... |
Most Pythonic way to find/check items in a list with O(1) complexity? | 40,064,377 | 3 | 2016-10-15T21:24:43Z | 40,064,454 | 7 | 2016-10-15T21:33:53Z | [
"python",
"algorithm",
"performance",
"python-3.x",
"time-complexity"
] | The problem I'm facing is finding/checking items in a list with O(1) complexity. The following has a complexity of O(n):
```
'foo' in list_bar
```
This has a complexity of O(n) because you are using the `in` keyword on a `list`. (Refer to [Python Time Complexity](https://wiki.python.org/moin/TimeComplexity))
However... | In general, it's impossible to find elements in a `list` in constant time. You could hypothetically maintain both a `list` and a `set`, but updating operations will take linear time.
You mention that your motivation is
> a list, and not a set, is largely due to the need to account for duplicate items within the list.... |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | 5 | 2016-10-17T15:40:08Z | 40,090,781 | 9 | 2016-10-17T15:55:19Z | [
"python",
"pandas"
] | I want to replace negative values with `nan` for only certain columns. The simplest way could be:
```
for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
```
`df` could have many columns and I only want to do this to specific columns.
Is there a way to do this in one line? Seems like this should be ea... | I don't think you'll get much simpler than this:
```
>>> df = pd.DataFrame({'a': np.arange(-5, 2), 'b': np.arange(-5, 2), 'c': np.arange(-5, 2), 'd': np.arange(-5, 2), 'e': np.arange(-5, 2)})
>>> df
a b c d e
0 -5 -5 -5 -5 -5
1 -4 -4 -4 -4 -4
2 -3 -3 -3 -3 -3
3 -2 -2 -2 -2 -2
4 -1 -1 -1 -1 -1
5 0 0 0 0 0
6... |
How to get a list of matchable characters from a regex class | 40,094,588 | 3 | 2016-10-17T19:54:32Z | 40,094,825 | 7 | 2016-10-17T20:08:55Z | [
"python",
"regex",
"python-3.x"
] | Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:
```
[\dA-C]
```
should give
```
['0','1','2','3','4','5','6','7','8','9','A','B','C']
``` | I think what you are looking for is [`string.printable`](https://docs.python.org/2/library/string.html#string.printable) which returns all the printable characters in Python. For example:
```
>>> import string
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\... |
More pythonic way of updating an existing value in a dictionary | 40,100,856 | 2 | 2016-10-18T06:16:31Z | 40,100,901 | 12 | 2016-10-18T06:19:33Z | [
"python",
"dictionary"
] | Lets assume I got a dictionary `_dict` and a variable `n`.
```
_dict = {'a': 9, 'b': 7, 'c': 'someValue'}
n = 8
```
I want to update just a single entry e.g. `{'b': 7}` only if the value of `n` is greater than the actual value of `b`.
The solution I got so far is
```
_dict.update({'b': n for key, value in _dict.item... | There is no point in looping if you just need to update one key:
```
_dict['b'] = max(_dict['b'], n)
```
The above sets `'b'` to the highest value of the two. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.