python: The word in List can't be removed - python-2.7

As you can see, i'm trying to delete the word in a list whose length is 1 or 2, but "P" and "ye" can't be found and removed!

Check out this code:
li = ['of','in','a','bb','abbb']
lii = []
for i in li:
j = len(i)
if j == 1 or j == 2:
lii.append(i)
for i in lii:
li.remove(i)
print li
Output:
['abbb']

You can't modify list while you iterate through it.
But you can do something like this:
L = ['of', 'P', 'representig', 'the', 'subs', 'et', 'ye', 'ti']
result = [i for i in L if len(i) != 1 and len(i) != 2]

Related

converting string characters in 2D list in Python 2.7

I create a 2D list, here is what I tried
list = [[] for i in range(2)]
data = 'abcd'
for row in data:
for col in row:
list[:0] = data
I got
['a','b','c','d', 'a','b','c','d','a','b','c','d','a','b','c','d']
But what I want is
['a','b']
['c','d']
Anyone can help?
You can to this without iteration:
data = 'abcd'
r = [list(data[:2]) , list(data[2:])]
print(r)
#[['a', 'b'], ['c', 'd']]
The following should work:
LIST_SIZE = 2
lists = [[] for _ in range(LIST_SIZE)]
data = 'abcd'
for i in range(LIST_SIZE):
for j in range(LIST_SIZE):
letter = data[LIST_SIZE * i + j]
lists[i].append(letter)

List value assignment within for loop

What can I do when I get the following error in this code?
def reverse_word(word):
index = len(word)
new_word = []
for i in range(index - 1, -1, -1):
new_word.append(word[i])
return ''.join(new_word)
def reverse_sentence(sentence):
l = sentence.split()
for i in l:
l[i] = reverse_word(i)
l = ' '.join(l)
print(l)
a = "Hello !Nhoj Want to have lunch?"
reverse_sentence(a)
TypeError: list indices must be integers or slices, not str.
What can I write instead of this line:
l[i] = reverse_word(i)
... this line: l[i] = reverse_word(i) throws an error because i is a string (word), but in l[i], i must be an index.
You probably wanted to do something like this:
words = sentence.plit()
new_sentence = []
for i,word in enumerate(words): #or just for word in words, you don't need the index
new_sentence.append(reverse_word(word))
and then join at return time return ' '.join(new_sentence)
This implementation follows your logic but uses strings instead of lists.
def reverse_word(word):
new_word = ''
for i in range(len(word) - 1, -1, -1):
new_word += word[i]
return new_word
def reverse_sentence(sentence):
r = ''
for word in sentence.split():
r += reverse_word(word) + ' '
return r[:-1]
>>> a = "Hello !Nhoj Want to have lunch?"
>>> reverse_sentence(a)
>>> 'olleH johN! tnaW ot evah ?hcnul'

python compare items in 2 list of different length and sequence/ duplicates should be considered

I'm trying to compare two lists of unequal length
list1=['a','b','d','b','c','d','e','f']
list2=['a','b','d','d']
list1 should be compared until the last element in list2(which is 'd') is found in list1.
Below is the desired output
output = ['b','c']
below is the code which i have
i = 0
j = 0
output = []
while(True):
if(list1[i] == list2[j]):
i += 1
j += 1
if (j == len(list2)):
break
else:
output.append(list1[i])
i = i + 1
is there any better way of doing the same?
Thanks for helping!
I think you want itertools.takewhile
from itertools import takewhile
def taker(l1, l2):
it = iter(l1)
for j in l2:
yield from takewhile(lambda x: x!=j, it)
list(taker(list1, list2)) is ['b', 'c']

Adding 2 lists to a dictonary in a loop in Python

I've been trying for a while to add 2 lists into my dictonary which i've created. The problem is though, that i want to run them into a loop so the first dictonary gets run 10 times and the second only one time.
Let me show you my code
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = ["Heart", "Spade", "Clubs", "Diamond"]
i = 0
k = 0
while i < len(list2):
while k < len(list1):
dictonary = dict(zip(list1, list2))
k = k+1
i = i+1
print(dictonary)
The output im getting is:
{1: 'Heart', 2: 'Spade', 3: 'Clubs', 4: 'Diamond'}
I cant understand why it wont print out
{1: 'Heart', 2: 'Heart', 3: 'Heart' etc...}
I know my loop works fine, but i might missunderstand the concept of adding two lists together to a dictonary?
Would appreciate some help here.
Thanks!
What you're trying to do won't work with a dictionary anyway.
The code can be fixed a bit
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = ["Heart", "Spade", "Clubs", "Diamond"]
dictonary={}
i = 0
k = 0
print(len(list2))
while i < len(list2):
k=0
while k < len(list1):
print(dictonary)
dictonary[list1[k]]=list2[i]
k = k+1
i = i+1
But you overwrite the values for the dictionary keys with each iteration of the outer loop. So the final contents of dictonary is {1: 'Diamond', 2: 'Diamond', 3: 'Diamond' etc...}
I think what you're trying to achieve can be done with a list of paired values:
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = ["Heart", "Spade", "Clubs", "Diamond"]
dictonary=[]
i = 0
k = 0
print(len(list2))
while i < len(list2):
k=0
while k < len(list1):
print(dictonary)
dictonary.append([list1[k],list2[i]])
k = k+1
i = i+1

Edit and append items to nested list - Python 2.7

I'm struggling folks. I have searched this forum and Google but can't find a simple answer that I can understand.
I have a nested list "plot" it would have hundreds of sublists all in the format of this sample:
plot = [['A', 21.09], ['A', 10.00], ['A', 20.99], ['B', 58.50], ['B', 17.69]]
I need to change the items in the sublists and store them in a new list "plotlists". These are the changes I need to make:
[?][0] (all first sublist items) if they are 'A' change to 0 if they are 'B' change to 1
[?][1] (2nd items) no change
[?][2] (3rd - new items) if [?][0] is 'A' then this item = -1 else it is [?][1] * 1.2
I have tried many ways to achieve this but the best I can get is a right mess of code that produces 3 new lists i.e.
Here is a minimal sample:
plot = [['A', 21.09], ['A', 10.00], ['A', 20.99], ['B', 58.50], ['B', 17.69]]
plot0 = []
plot1 = []
plot2 = []
for i in plot:
plot0.append(i[0])
plot1.append(i[1])
for i in plot0:
if i == 'A':
plot0.append(0)
elif 1 == 'B':
plot0.append(1)
for i in plot0:
if i == 'A':
plot2.append(-1)
elif i == 'B':
plot2.append(1.2)
Result:
plot0 = [0, 0, 0, 1, 1]
plot1 = [21.09, 10.00, 29.99, 58.50, 17.69]
plot2 = [-1, -1, -1, 1.2, 1.2]
Please can anyone show me ow to write this as a list comprehension that produces a result like this:
plotlists = [[0, 21.09, -1][0, 10.00, -1][0, 29.99, -1][1, 58.50, 70.56][1, 17.69, 21.23]]
This is a rather long list comprehension but it'll work:
new_list = [[0 if sublist[0] is 'A' else 1, sublist[1], -1 if sublist[0] is 'A' else 1.2*sublist[1]] for sublist in plot]
Update: Auto increment counter
new_list = [[i, 0 if sublist[0] is 'A' else 1, sublist[1], -1 if sublist[0] is 'A' else 1.2*sublist[1]] for i, sublist in zip(xrange(0, len(plot)), plot)]