How to Split a Tuple

Split tuple items to separate variables

Python can unpack sequences naturally.

domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')

How to separate a tuple into two independant lists?

Here comes your new hero, the zip function!

l = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a, b = zip(*l)

For future usages, we could say that it works in two different modes:

  • zip(*iterable) generates n iterables (being n the size of every tuple in the iterable), where every iterable contains the ith element of each tuple (the example of my answer).
  • zip(iterable_1, ..., iterable_n) generates a single iterable where every element is a tuple of size n containing the element of every iterable at the corresponding index.

How to split tuple in python

You need not split you can simply say

 a,b = k

How to split a list and into a tuple

You are close. You can append to another list called sublist and if you find a k append sublist to new_list:

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

new_lst = []
sublist = []
for element in lst:
if element != 'k':
sublist.append(element)
else:
new_lst.append(sublist)
sublist = []

if sublist: # add the last sublist
new_lst.append(sublist)

result = tuple(new_lst)
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

If you're feeling adventurous, you can also use groupby. The idea is to group elements as "k" or "non-k" and use groupby on that property:

from itertools import groupby

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
result = tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k)

print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

Thanks @YakymPirozhenko for the simpler generator expression

How to split a tuple into multiple columns in dictionary

  • Extract the keys as k1 and k2 instead of key, because you do .groupby on two columns.
  • Then create new_row with 'hr' as k1, and 'filename' as k2
  • Instead of assigning the returned values to popt, you can assign them to (x, y, z).
for (k1, k2), g in df.groupby(["hr", "filename"]):
...
(x, y, z), pcov = curve_fit(model, g['time'], g['NPQ'], p0=np.array([a, b, c]), absolute_sigma=True)
...
new_row = {'hr': k1, 'filename': k2, 'a': x, 'b': y, 'c': z}
new_df = new_df.append(new_row, ignore_index=True)
  • Alternatively, key is a tuple because the .groupby is on more than one column, so you can extract the separate values by calling the appropriate index.
    • Create new_row with 'hr' as key[0], and 'filename' as key[1]
  • If popt is a list or tuple, then you can assign the appropriate indices to 'a', 'b', and 'c'.
for key, g in df.groupby(["hr", "filename"]):
...
popt, pcov = curve_fit(model, g['time'], g['NPQ'], p0 = np.array([a, b, c]), absolute_sigma=True)
...
new_row = {'hr': key[0], 'filename': key[1], 'a': popt[0], 'b': popt[1], 'c': popt[2]}
new_df = new_df.append(new_row, ignore_index=True)

Splitting a list of tuples to several lists by the same tuple items

You could use a collections.defaultdict to group by colour:

from collections import defaultdict

lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue"), ("yo", "Green")]

colours = defaultdict(list)
for word, colour in lst:
colours[colour].append((word, colour))

print(colours)
# defaultdict(<class 'list'>, {'Blue': [('hello', 'Blue'), ('hey', 'Blue')], 'Red': [('hi', 'Red')], 'Green': [('yo', 'Green')]})

Or if you prefer using no libraries, dict.setdefault is an option:

colours = {}
for word, colour in lst:
colours.setdefault(colour, []).append((word, colour))

print(colours)
# {'Blue': [('hello', 'Blue'), ('hey', 'Blue')], 'Red': [('hi', 'Red')], 'Green': [('yo', 'Green')]}

If you just want the colour tuples separated into nested lists of tuples, print the values() as a list:

print(list(colours.values()))
# [[('hello', 'Blue'), ('hey', 'Blue')], [('hi', 'Red')], [('yo', 'Green')]]

Benefit of the above approaches is they automatically initialize empty lists for new keys as you add them, so you don't have to do that yourself.

How to split a tuple using train_test_split?

It seems that you're misunderstanding what train_test_split does. It is not expecting the shapes of the input arrays, what it does is to split the input arrays into train and test sets. So you must feed it the actual arrays, for instace:

X = np.random.rand(569,30)
y = np.random.randint(0,2,(569))
X_train, X_test, y_train, y_test = train_test_split(np.asarray(X),np.asarray(y),test_size = 0.25, random_state=0)

print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)

(426, 30)
(143, 30)
(426,)
(143,)

Split the Tuple with strings with the format as shown Below

I was able to figure out my answer. I sliced only the ordered dictionary out of the tuple first and then changed it to regular dictionary and finally concatenated all my dictionary values to make it look like a address.
** I also have the option to omit the zip code, or street name in my final formatted address by only selecting the dictionary values I need. Thanks to all who made time to look at this

z=list(x[0:1]) #convert the list
y=z[:1][0] #select only OrderedDict

p=dict(y) #convert to regular dictionary

# pull individual items to make an formatted address
main_address=p['AddressNumber']+' '+ p['StreetNamePreDirectional']+' '+ p['StreetName'] +' '+ p['StreetNamePostType']+','+ p['PlaceName']+','+ p['StateName']+','+ p['ZipCode']

print(main_address)
>>>output: 1893 W Malvern Ave,Fullerton,CA,92833


Related Topics



Leave a reply



Submit