How can i create list and add elements in python? - python-3.x

I am adding below readable code for creating a 'list' and all methods of add element. Here is the code:
Create list. Add element using append(),insert()
# Create lists
list1 = [1,4,6,8] # integer list.
list2 = [] # Empty List.
list3 = [1.2,'Raj',1] # mixed list.
# Print Created lists
print(list1)
print(list2)
print(list3)
# Add element using append(). Elements will be added at the last of list.
list1.append(11)
list1.append(12)
print(list1)
# Add elements in an empty list using for loop and append()
list2 = []
string = 'abcdef'
for ele in string:
list2.append(ele)
print(list2)
# Add element using insert(). Element will add at any position using index
list4 = ['r','j','s','h']
list4.insert(1,'a')
list4.insert(3,'e')
print(list4)

i have shared the link of image where both input and output is shown

Related

'list' object has no attribute 'split' in an NLP question

While running the following code snippet, I get the following error
'list' object has no attribute 'split'
for i in range(len(questions1)):
# Question strings need to be separated into words
# Each question needs a unique label
questions_labeled.append(TaggedDocument(questions1[i].split(), df[df.index == i].qid1))
questions_labeled.append(LabeledSentence(questions2[i].split(), df[df.index == i].qid2))
if i % 10000 == 0:
progress = i/len(questions1) * 100
print("{}% complete".format(round(progress, 2)))```
Because list has no split() only string objects have split.
The questions1 and questions2 objects seem to hold lists of strings (e.g., questions1 = [['this is a sample text', 'this is another one'],['this is some other text],...]), and not just strings (e.g., questions1 = ['this is a sample text', 'this is another one',...]). Hence the error (i.e., 'list' object has no attribute 'split'), as you are trying to split a list instead of a string. One way to solve this is to create a flast list out of each list of lists, before iterating over them, as described here. For example:
questions1 = [item for sublist in questions1 for item in sublist]
questions2 = [item for sublist in questions2 for item in sublist]

Find and replace list value in a dictionary python 3

I'm new to python. I'm trying to find and remove duplicate list values from the dictionary below:
dict = {'happy':['sun', 'moon', 'bills' 'chocolate'], 'sad':['fail', 'test', 'bills', 'baloon'], 'random': ['baloon', 'france', 'sun'] }
I want the dictionary dictionary to look like this after removing the duplicates from the list
expectd_dict = {'happy':['sun', 'moon', 'chocolate', 'bills'], 'sad':['fail', 'test','baloon'], 'random': ['france] }
I have looked for solutions on the internet but to no avail. I have tried creating an empty list and dict, iterating through the dictionary key and value, and also iterating through the list values, then adding it the to the empty list if not present, but I don't seem to be getting the desired result.
output_dict = {}
output_list = []
for key, value in d.items():
if key not in output_dict.values():
for i in value:
if i not in output_list:
output_list.append(i)
output_dict[key] = output_list
print(output_dict)
Think you want process lists in the order 'happy' -> 'random' -> 'sad'.
Loop in the list values, check if it seen in previous action, if not found, add it to the final list, add it to seen_values.
seen_values = set()
for key in ('happy', 'random', 'sad'):
final_list = []
for value in dict[key]:
if value in seen_values:
continue
seen_values.add(value)
final_list.append(value)
dict[key] = final_list

How can I group a list of strings by another list of strings using Python?

I have two lists:
List 1
filenames = ['K853.Z', 'K853.N', 'K853.E', 'K400.Z', 'K400.N', 'K400.E']
List 2
l = ['K853', 'K400']
I want to iterate through the filenames list and group the strings by the l list.
I've tried the below:
for name in filenames:
for i in l:
if i in name:
print(name)
But this just prints the first list. I've seen the Pandas groupby method but I can't figure out how to utilize it in this case.
you could just use a list generator like this:
new = [[name for name in filenames if(name.startswith(prefix))] for prefix in l]
This would provide you with a list of list, where for each index of l you would get a list of files with its prefix at the same index in the new list.

Copying list and then looping through first list and extending second list results in issue: Both lists get extended

The following python 3 code results in the tuple ('bla', 1.0) being added to both list1 and list2. Why? They don't point to the same place in memory.
#copy list1 to new list2:
for c in list1:
list2.append(c)
#loop through list1 and extend list2
>>> for idxc, c in enumerate(list1):
... for idxsc, sc in enumerate(c):
... list2[idxc][idxsc].extend([tuple(('bla', 1.0))])
The way to make a true copy of a list and all its contents, that will work on nested lists is by making a deep copy:
import copy
list2 = copy.deepcopy(list1)

Replace element of a list in python

I have list and i want to replace all the elements os the list with another elements.
Code:
list1 = ['1','1','3','4','5','2','3','4']
dict1 = {'dict1' : ['1','2','3','4','5'] ,'name':['su5','pra4','sa3','ma2','sri1']}
for x in range(len(dict1['dict1'])):
list1 = [word.replace(dict1['dict1'][x],dict1['name'][x]) for word in list1]
print(list1)
Actual Output:
['susri1', 'susri1', 'sa3', 'ma2', 'sri1', 'prama2', 'sa3', 'ma2']
Expected Output:
['su5','su5','sa3','ma2','sri1','pra4','sa3','ma2']
That's a very strange dictionary if you transform the dictionary so you can use it as a direct mapping then this is a relatively easy thing to do, e.g.:
>>> dict2 = dict(zip(dict1['dict1'], dict1['name']))
>>> [dict2[i] for i in list1]
['su5', 'su5', 'sa3', 'ma2', 'sri1', 'pra4', 'sa3', 'ma2']

Resources