Combine elements in a nested list - Python 3 [duplicate] - python

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python3 Concatenating lists within lists
I have
Nested_List = [['John', 'Smith'], ['1', '2', '3', '4']]
I want to manipulate this list such that I get this output:
Nested_List = [['John Smith'], ['1', '2', '3', '4']]
Basically the two elements in the first list were combined. How do I do this?

newElement = [' '.join(NestedList[0])]
Nested_List[0] = newElement
(modifies list, bad practice, but simple)

Related

How to remove and consecutively merge elements in a list [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
Let's say we have a list:
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', ..., 'a', '23', 'Q', '1']
I want to create a new list such as:
new_list = ['1234', '1537', '23L1', ..., 'a23Q1']
So, in this case I want to create a new list using "listA" by removing first two elements and merging all next elements in groups of 4, so the elements: 1, 2, 3, 4; are one element now.
How to approach this in case that I have a very long list to modify. Also, would be nice to know how to approach this problem in case I don't need to create a new list, if all I want is just to modify the list I already have (such as: listA = ['1234', '1537', '23L1', ..., 'a23Q1']). Thanks.
You can create an iterator over that list and then use zip with four identical copies of that iterator to combine each four consecutive elements:
>>> it = iter(listA[2:])
>>> [''.join(x) for x in zip(*[it]*4)]
['1234', '1537', '23L1', 'a23Q1']
itertools.islice allows you to avoid making a temporary copy of that list via slicing:
>>> import itertools
>>> it = itertools.islice(iter(listA), 2, None)
For your specific question, I would just loop through it.
I would do something like this. (Sorry if the format is a bit off this is one of my first answers) This will loop through and combine all complete sets of 4 elements. You could add custom logic if you wanted to keep the end as well. If you don't want to create a new list you can just use "ListA" and ignore the data scrubbing I did by using ListB.
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', 'a', '23', 'Q', '1']
listB = listA[2:] # remove first two elements
partialList = []
wholeList = []
position = 0
for element in listB:
if position < 4:
partialList.append(element)
position+=1
else:
wholeList.append(''.join(partialList))
position = 0
partialList = []
partialList.append(element)
print(wholeList)
If you don't need a new list you could just create one then set the old list to equal it afterwards. You could try this iterative approach:
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', 'a', '23']
new_list = [""]
count = 0
for item in listA:
if count % 4 == 0 and count > 0:
new_list.append("")
new_list[-1] += item
count += 1
listA = new_list
print(listA)
Output:
['stackoverflow12', '3415', '3723', 'L1a23']

Python: split one element in list [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Changing one element in a list from string to integer
(1 answer)
Closed 1 year ago.
Can not solve problem i have following list ['882','200','60'] sometimes it can be ['882','200'] i want get list like this [['8','8','2'], '200', '60'].
Another words no matter how many items are in the list, we always split the first item
You can use enumerate to get the first element:
l = ['882','200','60']
[e if i else list(e) for i,e in enumerate(l)]
output:
[['8', '8', '2'], '200', '60']
other examples
>>> [e if i else list(e) for i,e in enumerate(['123'])]
[['1', '2', '3']]
>>> [e if i else list(e) for i,e in enumerate(['882','200'])]
[['8', '8', '2'], '200']
mylist = ['882','200','60']
mylist[0] = list(mylist[0])

How to append element-wise of two lists in Python, where at least one of them is string [duplicate]

This question already has answers here:
Interleave multiple lists of the same length in Python [duplicate]
(11 answers)
Closed 2 years ago.
I would like to append element-wise of two lists (one in a string format). Suppose:
a = [1,2,3]
b = ['&','&','\\']
The output that I am looking is:
['1', '&', '2', '&', '3', '\\']
I tried the below code, but the answer is not the right one:
[str(x)+y for x,y in zip(a,b)]
Output: ['1&', '2&', '3\\']
Try this :
[k for i in zip(map(str, a), b) for k in i]
Output :
['1', '&', '2', '&', '3', '\\']
One limitation of using zip here would be it would iterate up to length of the smallest list, either a or b. For cases like the following :
a = [1, 2, 3, 4]
b = ['&','&','\\']
the above code would produce same result ['1', '&', '2', '&', '3', '\\'] and won't bother to go beyond 3 elements. To circumvent this, you can use zip_longest.

Python: Turn Nested List to Dictionary [duplicate]

This question already has answers here:
Get first element of sublist as dictionary key in python
(5 answers)
Closed 3 years ago.
I am trying to turn a nested list like this:
(Example list)
[['A','1','2','3'], ['B','4','5','6'],...]
To a dictionary that looks like this
{'A':'1','2','3','B': '4','5','6'}
Can someone please help me?
You can use dictionary comprehension:
lst = [['A','1','2','3'], ['B','4','5','6']]
{e[0]: e[1:] for e in lst}
This returns:
{'A': ['1', '2', '3'], 'B': ['4', '5', '6']}

Individually add each entry in a list to a string [duplicate]

This question already has answers here:
Appending the same string to a list of strings in Python
(12 answers)
Closed 4 years ago.
Nums = ['1', '2', '3', '4']
print(str('\n'.join(Nums)) + 'XXX')
Currently this returns
1
2
3
4XXX
I'd like to get the code to return xxx after each number rather than after only the last! Is there a way to process each one of these individually so it prints each entry in Nums + XXX?
Example:
1XXX
2XXX
...
Thanks!
In [1]: Nums = ['1', '2', '3', '4']
In [2]: print('\n'.join([i+'XXX' for i in Nums]))
1XXX
2XXX
3XXX
4XXX
To print each line separately:
In [5]: for i in Nums:
...: print('{}XXX\n'.format(i))
...:
1XXX
2XXX
3XXX
4XXX
It's similar to what you did with a small modification.
Nums = ['1', '2', '3', '4']
print('XXX\n'.join(Nums) + 'XXX\n')
I hope this helps!.

Categories

Resources