Manipulating the list of tuples in Python - python

I have a 2-element list like:
[(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
I want to get the first words of tuples that is I want to get a 2-element list as:
["sugar","father"]
I don't know how can I achive this since I am unfamilier with u' notation. Can anyone help or give some hints?

Using str methods
Ex:
d = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
print([i[1].split("+")[0].split("*")[1].replace('"', "").strip() for i in d])
Output:
[u'sugar', u'father']
str.split to split string by ("+" and "*")
str.replace to replace extra quotes
str.strip to remove all trailing or leading space.

You can find the value of an index location using square brackets.
myList[index]
In nested lists:
myList[indexInOuterList][indexInInnerList]
For your situation:
myList[indexInList][indexInTuple]
mylist = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
myList[0][0] #This is the integer 2

Related

Replace dashes with whitespaces for all elements across a tuple?

I'm building off of these two questions because they don't quite answer my question:
How to change values in a tuple?
Python: Replace "-" with whitespace
If I have a tuple like this:
worldstuff = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi'), ...]
How do I replace dashes with whitespaces for all of the elements across all lists in a tuple? The previous Stack Overflow question covers changing the specific index of one list in a tuple, but not if there are multiple occurances of an element needing to be replaced.
I've tried doing the following, which doesn't quite work:
worldstuff_new = [x.replace('-', ' ') for x in worldstuff]
But if I do it for a specific list in the tuple, it works for that tuple list. I'm trying to avoid having to do separate lists and instead trying to do it all at once.
worldstuff_new = [x.replace('-', ' ') for x in worldstuff[0]]
I understand that tuples are immutable, which is why I am having trouble figuring this out. Is this possible? Would appreciate any help - thanks.
Correct expression:
a = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi')]
b = [tuple([x.replace('-', ' ') for x in tup]) for tup in a]
>>> b
[('Hi', 'Hello World', 'Earth'), ('Hello World', 'Hi')]
A few notes:
Please don't clobber builtins (tuple).
What you have is actually not a tuple, but a list of tuples.
As you note, tuples are immutable; but you can always build new tuples from the original ones.
(Speed) Why tuple([x.replace ...]) (tuple of a list comprehension) instead of tuple(x.replace ...) (tuple of the output of a generator)? Because the former is slightly faster.
first of everything, don't name any variable tuple it's a builtin function and when you name a variable tuple you miss that method
def changer(data):
if type(data) == str:
return data.replace("-", " ")
elif type(data) == list:
return [changer(x) for x in data]
elif type(data) == tuple:
return tuple(changer(x) for x in data)
tpl = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi')]
changer(tpl)
output:
[('Hi', 'Hello World', 'Earth'), ('Hello World', 'Hi')]
tuple_old = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi')]
tuple_new = [
tuple([x.replace('-', ' ') for x in tup]) for tup in tuple_old
]
print(tuple_new)
FWIW, tuples are the things in parentheses. Lists are in square brackets. So you have a list of tuples, not a tuple of lists.
There are a few things that might help you to understand:
You cannot change a tuple or a string. you can only create a new one with different contents.
All the functions that "modify" a string are actually just creating a new string that has been modified from the original. Your original question that you referenced also slightly mis-understood one of the quirks of python where you can iterate over the characters in a string, but due to python not having a character datatype, they just end up as new strings. tldr; replacing "-" with " " looks just like this:
print("old-str".replace("-", " "))
This will generate a new string with all the dashes replaced.
Now you need to extend this to creating a new tuple of strings. You can create a new tuple with the built-in-function (which you had previously accidentally overwrote with a variable) tuple and passing in some sort of iterable. In this case I will use a generator expression (similar to list comprehension but without the square brackets) to create this iterable:
tuple(entry.replace("-", " ") for entry in old_tup)
finally you can apply this to each tuple in your list either by creating a new list, or by over-writing the values in the existing list (example shows creating a new list with a list comprehension):
[tuple(entry.replace("-", " ") for entry in old_tup) for old_tup in worldstuff ]
This might help:
worldstuff_new = [tuple(x.replace('-', ' ') for x in t) for t in worldstuff]
If you want a different way to do this you could use the map function like so.
tuples = [('Hi','Hello-World', 'Earth'), ('Hello-World', 'Hi'), ('Te-st', 'Te-st2')]
new_tuples = list(map(lambda tup: tuple(item.replace('-', ' ') for item in tup), tuples))
output:
[('Hi', 'Hello World', 'Earth'), ('Hello World', 'Hi'), ('Te st', 'Te st2')]

Turning a string of numbers list into a list of integers tuple [duplicate]

I have a list of strings in this format:
['5,6,7', '8,9,10']
I would like to convert this into the format:
[(5,6,7), (8,9,10)]
So far I have tried this:
[tuple(i.split(',')) for i in k]
And I obtain:
[('5','6','7'), ('8','9','10')]
I am a bit stuck on how to simply convert the strings into tuples of integers. Thank you
If your strings are strings representation of number, then:
[tuple(int(s) for s in i.split(',')) for i in k]
The following solution is for me the most readable, perhaps it is for others too:
a = ['5,6,7', '8,9,10'] # Original list
b = [eval(elem) for elem in a] # Desired list
print(b)
Returns:
[(5, 6, 7), (8, 9, 10)]
The key point here being the builtin eval() function, which turns each string into a tuple.
Note though, that this only works if the strings contain numbers, but will fail if given letters as input:
eval('dog')
NameError: name 'dog' is not defined
Your question requires the grouping of elements. Hence, an appropriate solution would be:
l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]
This outputs:
[(5, 6, 7), (8, 9, 10)]
As desired.
listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)
source: https://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288

remove spaces/commas from a variable to add to a string

I need it to look like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3333)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
instead it looks like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3, 3, 3, 3)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
Code:
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
for l in range(0, 4):
trypass=(i,j,k,l)
#print(i,j,k,l, sep='')
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= {}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).strip(','))
strip only strips from the beginning and end of the string, it doesn't strip the characters from the middle.
Your problem isn't really stripping, it's adding unnecessary junk in the first place by directly stringifying the tuple.
To fix both, convert trypass to a string up front with no joiner characters in the middle:
trypass = ''.join(map(str, (i,j,k,l)))
A side-note: You could shorten this a lot with itertools.product to turn four loops into one (no arrow shaped code), and avoid repeatedly stringifying by converting the range elements to str only once, directly generating trypass without the intermediate named variables:
from itertools import product
for trypass in map(''.join, product(map(str, range(0, 4)), repeat=4)):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= ({})&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).)
.format(trypass) will format the tuple as a string using the default tuple formatting rules, e.g. (3, 3, 3, 3). Instead you should explicitly tell it how to format the string, like:
.format(''.join(str(i) for i in trypass))
You have a tuple that you want to reduce to a string.
>>> trypass = (3,3,3,3)
>>> ''.join(str(i) for i in trypass)
'3333'
Or, since you know there are exactly 4 digits,
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))
Or, just iterate over the 4-digit numbers directly. itertools.product can generate the tuples for you.
import itertools
for trypass in itertools.product("0123", repeat=4):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))

Convert a list of strings to a list of tuples in python

I have a list of strings in this format:
['5,6,7', '8,9,10']
I would like to convert this into the format:
[(5,6,7), (8,9,10)]
So far I have tried this:
[tuple(i.split(',')) for i in k]
And I obtain:
[('5','6','7'), ('8','9','10')]
I am a bit stuck on how to simply convert the strings into tuples of integers. Thank you
If your strings are strings representation of number, then:
[tuple(int(s) for s in i.split(',')) for i in k]
The following solution is for me the most readable, perhaps it is for others too:
a = ['5,6,7', '8,9,10'] # Original list
b = [eval(elem) for elem in a] # Desired list
print(b)
Returns:
[(5, 6, 7), (8, 9, 10)]
The key point here being the builtin eval() function, which turns each string into a tuple.
Note though, that this only works if the strings contain numbers, but will fail if given letters as input:
eval('dog')
NameError: name 'dog' is not defined
Your question requires the grouping of elements. Hence, an appropriate solution would be:
l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]
This outputs:
[(5, 6, 7), (8, 9, 10)]
As desired.
listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)
source: https://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288

Converting lists of tuples to strings Python

I've written a function in python that returns a list, for example
[(1,1),(2,2),(3,3)]
But i want the output as a string so i can replace the comma with another char so the output would be
'1#1' '2#2' '3#3'
Any easy way around this?:)
Thanks for any tips in advance
This looks like a list of tuples, where each tuple has two elements.
' '.join(['%d#%d' % (t[0],t[1]) for t in l])
Which can of course be simplified to:
' '.join(['%d#%d' % t for t in l])
Or even:
' '.join(map(lambda t: '%d#%d' % t, l))
Where l is your original list. This generates 'number#number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').
The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.
You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.
ll = [(1,1), (2,2), (3,3)]
['%d#%d' % aa for aa in ll]
This would return a list of strings like:
['1#1', '2#2', '3#3']
You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.
' '.join([str(a)+"#"+str(b) for (a,b) in [(1,1),(2,2),(3,3)]])
or for arbitrary tuples in the list,
' '.join(['#'.join([str(v) for v in k]) for k in [(1,1),(2,2),(3,3)]])
In [1]: ' '.join('%d#%d' % (el[0], el[1]) for el in [(1,1),(2,2),(3,3)])
Out[1]: '1#1 2#2 3#3'
[ str(e[0]) + ',' + str(e[1]) for e in [(1,1), (2,2), (3,3)] ]
This is if you want them in a collection of string, I didn't understand it if you want a single output string or a collection.
[str(item).replace(',','#') for item in [(1,1),(2,2),(3,3)]]
You only need join and str in a generator comprehension.
>>> ['#'.join(str(i) for i in t) for t in l]
['1#1', '2#2', '3#3']
>>> ' '.join('#'.join(str(i) for i in t) for t in l)
'1#1 2#2 3#3'
you could use the repr function and then just replace bits of the string:
>>> original = [(1,1),(2,2),(3,3)]
>>> intermediate = repr(original)
>>> print intermediate
[(1, 1), (2, 2), (3, 3)]
>>> final = intermediate.replace('), (', ' ').replace('[(','').replace(')]','').replace(', ','#')
>>> print final
1#1 2#2 3#3
but this will only work if you know for certain that none of tuples have the following character sequences which need to be preserved in the final result: ), (, [(, )], ,

Categories