How to unpack tupled list in python - python

I have tupled list like this.
[('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
How to unpack this to get the result like below.
ram,18
kp,12
nm,14
Thanks.

You can just iterate over the list to unpack each piece.
mylist = [('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
for tup in mylist:
print ",".join(tup)
Output:
"ram,18"
"kp,12"
"nm,14"
If you do not like the quotes, just remove them after the join.
for tup in mylist:
print ",".join(tup).replace('"','')
Output:
ram,18
kp,12
nm,14

ta = [('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
for t in ta:
print ','.join(t)
or you can access individual items by indexing them:
ta[1]

Using a simple for loop should be enough.
Eg:
items = [('ram', '18'), ('kp', '12'), ('nm', '14')]
for label, value in items:
print label + "," + value

Related

How to change list of list to a string

I need to get:
'W1NaCl U1NaCl V1NaCl'
from:
[['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
How to get required output in pythonic way
items = [['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
res = " ".join([item[0] for item in items])
Which yields: W1NaCl U1NaCl V1NaCl
You can do:
[[i] for i in 'W1NaCl U1NaCl V1NaCl'.split()]
Split will chop it into words, and the list comprehension will make the inner-arrays

Converting a list with multiple values into a dictionary

I have the following list and am wanting to convert it into a dictionary where the 4 digit value at the start of each item becomes the id.
['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
I have tried many different methods but it doesn't seem to work.
You can use str.split, map and dictionary comprehension
# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}
OUTPUT:
Out[35]:
{'3574': ['A+', '2021-03-24'],
'3575': ['O+', '2021-04-03'],
'3576': ['AB-', '2021-04-09'],
'3580': ['AB+', '2021-04-27'],
'3589': ['A+', '2021-05-08'],
'3590': ['B-', '2021-05-11']}
You can use dictionary comprehension with str.split:
lst = [
"3574,A+,2021-03-24",
"3575,O+,2021-04-03",
"3576,AB-,2021-04-09",
"3580,AB+,2021-04-27",
"3589,A+,2021-05-08",
"3590,B-,2021-05-11",
]
out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)
Prints:
{
3574: ["A+", "2021-03-24"],
3575: ["O+", "2021-04-03"],
3576: ["AB-", "2021-04-09"],
3580: ["AB+", "2021-04-27"],
3589: ["A+", "2021-05-08"],
3590: ["B-", "2021-05-11"],
}
Here is the code to do what I believe you asked for. I have also added comments in the code for a bit more clarification.
my_list = ['3574,A+,2021-03-24',
'3575,O+,2021-04-03',
'3576,AB-,2021-04-09',
'3580,AB+,2021-04-27',
'3589,A+,2021-05-08',
'3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into
print("Your list:", my_list, "\n")
for item in my_list:#cycles through every item in your list
ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
print(ID + ": " + value)
my_dict[ID] = value#Add the ID and value to your dictionary
print("\n" + "Your desired dictionary:", my_dict)
Which outputs this:
Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11
Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}
Enjoy!
TRY:
result = dict(i.split(',', 1) for i in lst)
OUTPUT:
{'3574': 'A+,2021-03-24',
'3575': 'O+,2021-04-03',
'3576': 'AB-,2021-04-09',
'3580': 'AB+,2021-04-27',
'3589': 'A+,2021-05-08',
'3590': 'B-,2021-05-11'}

combine two strings in python

I have a list1 like this,
list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
I want to get a new list2 like this (joining first element with second element's second entry);
list2 = [('my2', 2),('name8', 3)]
As a first step, I am checking to join the first two elements in the tuple as follow,
for i,j,k in list1:
#print(i,j,k)
x = j.split('.')[1]
y = str(i).join(x)
print(y)
but I get this
2
8
I was expecting this;
my2
name8
what I am doing wrong? Is there any good way to do this? a simple way..
try
y = str(i) + str(x)
it should works.
The str(i).join(x), means that you see x as an iterable of strings (a string is an iterable of strings), and you are going to construct a string by adding i in between the elements of x.
You probably want to print('{}{}'.format(i+x)) however:
for i,j,k in list1:
x = j.split('.')[1]
print('{}{}'.format(i+x))
Try this:
for x in list1:
print(x[0] + x[1][2])
or
for x in list1:
print(x[0] + x[1].split('.')[1])
output
# my2
# name8
You should be able to achieve this via f strings and list comprehension, though it'll be pretty rigid.
list_1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
# for item in list_1
# create tuple of (item[0], item[1].split('.')[1], item[2])
# append to a new list
list_2 = [(f"{item[0]}{item[1].split('.')[1]}", f"{item[2]}") for item in list_1]
print(list_2)
List comprehensions (and dict comprehensions) are some of my favorite things about python3
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3
Going with the author's theme,
list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
for i,j,k in list1:
extracted = j.split(".")
y = i+extracted[1] # specified the index here instead
print(y)
my2
name8
[Program finished]

Iterate through a list using re.sub()

I am trying to replace the valuse in a list with the long format name.
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
I am running the following script:
for value in value_list:
value = re.sub(r'Gi', 'GigabitEthernet', value)
print value
print value_list
This is my out put:
GigabitEthernet1/0/8
GigabitEthernet1/0/31
GigabitEthernet1/0/32
GigabitEthernet1/0/33
GigabitEthernet1/0/34
GigabitEthernet1/0/23
GigabitEthernet1/0/27
I just need to change the values in the list, it seems doing it all wrong. Can anyone help me do this in an efficient manner so i dont need to create another list from the individual outputs??
Then use list comprehension instead:
print([re.sub(r'Gi', 'GigabitEthernet', value) for value in value_list])
Output:
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
This code updates existing list:
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
for i in range(len(value_list)):
value_list[i] = re.sub(r'Gi', 'GigabitEthernet', value_list[i])
print value_list
# ['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
Using map
Ex:
import re
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
value_list = list(map(lambda value: re.sub(r'Gi', 'GigabitEthernet', value), value_list))
print(value_list)
Output:
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
To change the list "in-place" you need to set each item in the list to the new value. Just doing value = re.sub(r'Gi', 'GigabitEthernet', item) doesn't change the value stored in the list.
This code changes the values in the list:
>>> value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
>>> for idx, item in enumerate(value_list):
... value_list[idx] = re.sub(r'Gi', 'GigabitEthernet', item)
...
>>> value_list
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
The enumerate function generates the list indexes for you, so you can iterate over your list pythonically (for item in mylist) rather than indexing directly (for i in range(len(mylist))) which produces less readable code.

How to get the values in split python?

['column1:abc,def', 'column2:hij,klm', 'column3:xyz,pqr']
I want to get the values after the :. Currently if I split it takes into account column1, column2, column3 as well, which I dont want. I want only the values.
This is similar to key-values pair in dictionary. The only dis-similarity is that it is list of strings.
How will I split it?
EDITED
user_widgets = Widgets.objects.filter(user_id = user_id)
if user_widgets:
for widgets in user_widgets:
widgets_list = widgets.gadgets_list //[u'column1:', u'column2:', u'column3:widget_basicLine']
print [item.split(":")[1].split(',') for item in widgets_list] //yields list index out of range
But when the widgets_list value is copied from the terminal and passed it runs correctly.
user_widgets = Widgets.objects.filter(user_id = user_id)
if user_widgets:
for widgets in user_widgets:
widgets_list = [u'column1:', u'column2:', u'column3:widget_basicLine']
print [item.split(":")[1].split(',') for item in widgets_list] //prints correctly.
Where I'm going wrong?
You can split items by ":", then split the item with index 1 by ",":
>>> l = ['column1:abc,def', 'column2:hij,klm', 'column3:xyz,pqr']
>>> [item.split(":")[1].split(',') for item in l]
[['abc', 'def'], ['hij', 'klm'], ['xyz', 'pqr']]
Nothing wrong with a 'for' loop and testing if your RH has actual data:
li=[u'column1:', u'column2:', u'column3:widget_basicLine', u'column4']
out=[]
for us in li:
us1,sep,rest=us.partition(':')
if rest.strip():
out.append(rest)
print out # [u'widget_basicLine']
Which can be reduced to a list comprehension if you wish:
>>> li=[u'column1:', u'column2:', u'column3:widget_basicLine', u'column4']
>>> [e.partition(':')[2] for e in li if e.partition(':')[2].strip()]
[u'widget_basicLine']
And you can further split by the comma if you have data:
>>> li=[u'column1:', u'column2:a,b', u'column3:c,d', u'column4']
>>> [e.partition(':')[2].split(',') for e in li if e.partition(':')[2].strip()]
[[u'a', u'b'], [u'c', u'd']]

Categories

Resources