How do you split a string inside a list? - python-3.x

I got this type of strings inside a list :
[['AAAA-BBBBBBB-10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00', '000', 'BBBBBBB', 'AAAAA:00'], [
when i export this list to csv the strings inside the commas (,) are in different cells but 'AAAA-BBBBBBB-10.00.00.0' is all in one cell. I wanted it to look like this:
[['AAAA-BBBBBBB','10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00', '000', 'BBBBBBB', 'AAAAA:00'], [
so when i export it to csv file the strings 'AAAA-BBBBBBB','10.00.00.0' will be in 2 different cells.
I tried:
dp1 = [d.replace("-1"," 1").split() for d in data]
but it doesnt work it seems its ignoring it!

You can enumerate the elements of the outer list, change the composition of the 1st item of the inner list and assing it back to your outer list:
data = [['AAAA-BBBBBBB-10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00',
'000', 'BBBBBBB', 'AAAAA:00'],
[]]
for idx, d in enumerate(data):
if d:
orig = d[0].replace("-1"," 1").split() # create a 2 part list
d = orig + d[1:] # use list slicing
data[idx] = d # assign it back to your big list
print(data)
Output:
[['AAAA-BBBBBBB', '10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00',
'000', 'BBBBBBB', 'AAAAA:00'],
[]]

Related

Python nested list conditional delete

I have a list of lists where some lists are not complete. I.e.:
data = [
['id1',1],
['id2'],
['id3'],
['id4'],
['id5',1]
]
I want to create a new list that contains only "full" lists.
Desired output:
[
['id1',1],
['id5',1]
]
I have tried:
new_data = [i for i in data if i[1]]
However, this returned:
List index error: Index out of range
I find it odd because the if[1] is right there.
Question
Is there a simple fix for a one-line approach, or must we use a for loop?
Instead of trying accessing the values, check for length:
new_data = [i for i in data if len(i) == 2]

For the given the two sequences, I am getting a error for input while writing a program to combine two sequences and arrange them alphabetically?

def all_people(people_1, people_2):
# update logic here
people_1.split(',')
people_2.split(',')
people_1.extend(people_2)
print(people_1.sort())
people_1 = input()
people_2 = input()
all_people(people_1, people_2)
For the given the two sequences, I am getting a AttributeError: 'str' object has no attribute 'extend'
The problem is :how to write a program to combine two sequences and arrange them alphabetically.
This is because when you input your list into people_1 it becomes a string.
So for example, if you input ['Person 1', 'Person 2'] into people_1, then people_1 = "['Person 1', 'Person 2']"(A string). So in order to apply .extend() to people_1 you first have to turn it into a list.
Try this:
import ast
people_1 = ast.literal_eval(input())
people_2 = ast.literal_eval(input())
(Be sure to import ast)
That way your input will automatically be changed from a string to a list and you can apply .extend.
str.split will not transform the split string into a list (even without the type difference, strings are immutable), but return a list. To use it, you will need to assign it to a variable. If you don't need the original string, you can just overwrite it1.
list_1 = input('first list, separated by , -> ')
list_1 = list_1.split(',')
list_2 = input('second list, separated by , -> ').split(',')
list_1.extend(list_2)
print(list_1)
Will result in
first list, separated by , -> a,b,some value with spaces
second list, separated by , -> in,the,second,one
['a', 'b', 'some value with spaces', 'in', 'the', 'second', 'one']
1 This applies to a simple case where you convert a data structure once. Don't go around overwriting variables with totally unrelated stuff all over the place.

Delete sub-list from list in python

I need to remove the sub lists from a list in Python.
For example: The main list A contains
A=[ 'a,b,c', 'd,e,f' , 'g,h,i' , 'g,l,m' , 's,l,k' , 'd,k,l', 'a,g,d' ]
I need to remove the sub lists from A which begin with the items in the following list:
B = ['g','d']
so that Final List A = [ 'a,b,c', 's,l,k' , 'a,g,d' ]
Thanks in advance
Using list comprehension:
print([x for x in A if x[0] not in ['g', 'd']])
You can do it using list comprehension and split(",").
print([e for e in A if e.split(",")[0] not in B])
Output
['a,b,c', 's,l,k', 'a,g,d']
Your output above for your approach is wrong.
2nd Element 'd,e,f' should also be removed as start element 'd' is in second list.

Merging item in two lists with a separator

I have two separate lists, "a" and "b". I'm trying to merge them together so it shows the items in the two lists with a hyphen in between.
I tried to using the zip and join functions but I wasn't able to solve the issue.
a = ['USA', 'Australia', 'Netherlands', 'Sweden', 'France', 'Spain']
b = ['Washington', 'Canberra', 'Amsterdam', 'Stockholm', 'Paris', 'Barcelona']
##I tried using zip
c = CT = zip(a,b)
##I got:
[('USA', 'Washington'),
('Australia', 'Canberra'),
('Netherlands', 'Amsterdam'),
('Sweden', 'Stockholm'),
('France', 'Paris'),
('Spain', 'Barcelona')]
Tried to use join as well, but that didn't work
Ideally, the output should be:
USA-Washington
Australia-Canberra
Netherlands-Amesterdam
Sweden-Stockholm
France-Paris
Spain-Barcelona
Any help would be appreciated.
You can apply a list comprehension over the zipped items:
[x + '-' + y for x,y in zip(a,b)]
You can apply join to each result of zip.
c = ['-'.join(x) for x in zip(a, b)]
Or you can use a for loop.
c = []
for i in range(min(len(a), len(b))):
c.append('{}-{}'.format(a[i], b[i]))

Adding dictionary values to a list?

I have the following:
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
How can I iterate through the dictionary and append one of those values into that list? What if I only want to append the value of 'key2'.
If you only want to append a specific set of values you don't need to iterate through the dictionary can simply add it to the list
list_of_values.append(x["key2"])
However, if you insist on iterating through the dictionary you can iterate through the key value pairs:
for key, value in x.items():
if key == "key2":
list_of_values.append(value)
If you really want to iterate over the dictionary I would suggest using list comprehensions and thereby creating a new list and inserting 'key2' :
list_of_values = [x[key] for key in x if key == 'key2']
because that can be easily extended to search for multiple keywords:
keys_to_add = ['key2'] # Add the other keys to that list.
list_of_values = [x[key] for key in x if key in keys_to_add]
That has the simple advantage that you create your result in one step and don't need to append multiple times. After you are finished iterating over the dictionary you can append the list, just to make it interesting, you can do it without append by just adding the new list to the older one:
list_of_values += [x[key] for key in x if key in keys_to_add]
Notice how I add them in-place with += which is exactly equivalent to calling list_of_values.append(...).
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
list_of_values.append(x['key2'])

Resources