how do i extract a partial value from a string in python? - python

I have the following string:
(1, 2, 3, 4)
I want to convert it to just the last two values:
(3, 4)
In my actual code all four fields are whole numbers but vary greatly in length. I've tried doing this with both regex and 'for' statements as well as trying the various answers to similar questions here on SO but so far no luck.

This gives you the last two terms in your tuple:
>> a = (1,2,3,4)
>> a[-2:]
(3,4)

It sounds like you want to use the slice operator.
Edit: Perhaps this is a better link. Scroll down a bit for the slice notation stuff. The examples deal with strings, but it should work with any sequence type.

If (1,2,3,4) is tuple:
data = (1,2,3,4)
newData = data[-2:]
If you have '(1,2,3,4)' then:
import ast
data = ast.literal_eval('(1,2,3,5)')
newData = data[-2:]
Or in case you have to split such list in a certain value:
def get_slice(inputData, searchVal):
if searchVal in inputData and inputData.index(searchVal) < len(inputData):
return inputData[inputData.index(searchVal)+1:]
return ()
get_slice((1,2,3,4),2)

Related

Return the most common element as a string not a list python

I know I can use the counter from collections to return the most common elements in an array or a string and so on. However this counter returns a list of the n most common elements and their counts from the most common to the least. Lets say I want to find most common characters in a string using counter:
Counter('abracadabra').most_common(1)
This will however return an answer of type list like this:
[('a', 5)]
Is there a way to return only the character "a" as a type of string without the times it is repeated?
Thanks for the help!
How about just grabbing the string from the output of Counter.most_common()?
something like:
Counter('abracadabra').most_common(1)[0][0]

Python convert list of tuples into single tuple

Is there a way to convert a list of tuples into a single tuple? I have received a list of tuples from cursor.fetchall() but would like to make this into a single tuple:
curr_table_columns = cursor.fetchall()
For example:
[(u'w_id',), (u'w_name',), (u'w_street',)]
becomes
[(u'w_id', u'w_name', u'w_street')]
With itertools.chain, it's trivial. from itertools import chain and you can do either:
[tuple(chain.from_iterable(curr_table_columns))]
or:
[tuple(chain(*curr_table_columns))]
The former is preferred for long or unbounded iterable inputs (though don't wrap in tuple for unbounded!); for a small input (particularly one that's already a list or tuple), the latter is slightly slower, but fine. Either one is going to be significantly faster than a genexpr and indexing for inputs of any size at all.
Try this:
a=[(u'w_id',), (u'w_name',), (u'w_street',)]
print [tuple([i[0] for i in a])]
Output:
[(u'w_id', u'w_name', u'w_street')]
Not efficient*, but it is simple:
>>> ts = [(u'w_id',), (u'w_name',), (u'w_street',)]
>>> sum(ts, ())
('w_id', 'w_name', 'w_street')
So, just wrap it in a list if you must:
>>> result = [sum(ts, ())]
>>> result
[('w_id', 'w_name', 'w_street')]
*Warning: scales quadratically. Some might be inclined to let is slide for joining some column names into a single container. Definitely don't try to process millions of tuples this way.
Use itertools solution for linear time.
This function can convert listWidgets item into single tuple and also convert multiple element of tuple into single element tuple : Used for Sqlite3 and data query from listwidgets.
def tuple_converter(self,item):
target = ''
for i in item:
target += i + " "
target = target.rstrip()
target = tuple(target.split(","))
return target
#syntax name = tuple_converter(tuple((item).split()))
'''

Python - convert a list in an array

I got a list of values and i would like to convert it in an array in order to extract easily columns, but i m embarassed with " which doesn t allow to use : " x = np.array(a, dtype=float)"
['"442116.503118","442116.251106"',
'"442141.502863","442141.247462"',
...
The message obtained is :
"could not convert string to float: "442116.503118","442116.251106""
Answering based on the VERY limited information given, but if that is your list it looks like a list of nested strings, not floats. Try
x = np.array([float(i.replace("\"","")) for i in a], dtype=float)"
This is just wrong... This does the trick for me though:
import numpy as np
wtf = ['"442116.503118","442116.251106"',
'"442141.502863","442141.247462"']
to_list = []
for nest1 in wtf:
nest2 = nest1.split(',')
for each in nest2:
to_list.append(float(each.strip('"')))
to_array = np.asarray(to_list)
Not exactly elegant. You need to deal with each level of nesting in your input data. I'd recommend you reconsider the way you're formatting the data you're inputting.

How to unpack only some arguments from zip, not all?

My sql query:
select id,value,zvalue from axis
gives me result like this:
ans=(1,23,34)(12,34,35)(31,67,45)(231,3412,234)
now if i want all these 3 variables as 3 different lists
id,value,zvalue=zip(*ans)
it will give me 3 separate lists.
but if i only want id and value as separate lists.It will give me TOO MANY VALUES TO UNPACK ERROR.
id,value =zip(*ans)
is there any way where i can create any number of lists from sql query.because if there are 10 parameters in the query , i have to use all the parameters while using ZIP???
please help
The number of arguments must match, this is a rule in Python 2. For Python 3, you can use * to capture into a list.
The common pythonic (2.x) workaround is to use _ to denote variables you won't use, i.e.:
id,value,_ = zip(*ans) # only works for exactly three values
As DSM commented, for Python 3, you can use * to grab "remaining" args as a list:
id, value, *_ = zip(*ans) # _ will be a list of zero or more args
Or, simplest, just slice the return from zip:
id,value = zip(*ans)[:2] # ignore all but first two values
If you are using Python 3 you can use this for unpacking n additional elements:
In [0]: a, b, *_ = (1, 2, 3, 4)
In [1]: a
1
I think you might be looking for something like this:
ids = [t[0] for t in ans]
values = [t[1] for t in ans]
The first list comprehension gets the first column in all tuples in ans, that is, the id column. The second list comprehension gets the second column for all tuples in ans, that is, the value column.

python: The correct way to assign a value from itertools.permutations()?

The following code creates a multi dimensional list (not sure if that's the Pythonic was of saying it. PHP guy here)
patterns.append(list(itertools.permutations('1234567',7)))
the value of patterns becomes:
([
[1,2,3,4,5,6,7],
[1,2,3,4,5,7,6], ...
])
What I want is for the result to be like this:
([1,2,3,4,5,6,7], [1,2,3,4,5,7,6]...)
If i try doing:
patterns = list(itertools.permutations('1234567',7))
the result is a list of individual numbers
123445671234576
What am I missing?
Thanks,
You extend() instead of append().
patterns.extend(itertools.permutations('1234567',7))
This also makes list() redundant because extend() works on iterables.
This assumes you are ok with the permutations themselves being tuples. Your question is confusing because you the notation doesn't correspond with what you wrote in words.
If you need to get
([1,2,3,4,5,6,7], [1,2,3,4,5,7,6]...)
than you can use:
from itertools import permutations
patterns = tuple(list(int(y) for y in x) for x in permutations('1234567',7))
OR you can use xrange instead of '1234567' if you need to get numbers:
patterns = tuple(list(x) for x in permutations(xrange(1,8),7))
You can get a tuple of lists with
tuple(list(p) for p in itertools.permutations('1234567', 7))
If you want integers instead of one-element strings, then an easy and general way to do that is
digits = [int(digit) for digit in '1234567']
tuple(list(p) for p in itertools.permutations(digits, 7))

Categories

Resources