Creating multiple list from loops - python

I want to make multiple lists with my for loops, My code is:
for port in portlist1:
print port.getname(),port.getsize()
for register in port.getregisters():
j=j+1
print j
j=0
Output is:
B 10
1
C 15
1
F 30
1
I want to make list every time:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
Can someone help me here?

lists = []
for port in portlist1:
l = [[port.getname(), port.getsize()]]
for register in port.getregisters():
j=j+1
l.append(j)
lists.append(l)
j=0

It's not clear what was the value of j before the loop, but it looks like you are using it to measure the length of port.getregisters(). Try this one-liner:
result = [[[port.getname(), port.getsize()], len(port.getregisters())] for port in portlist1]

It's a bad idea to make a new list each time, you should just go with nesting each list. If the amount of ports is static, you can use vars()['listX'].. But still not really recomended. You should go with the answer given by kroolik or alecxe
But if you REALLY need someting like..:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
You can use:
lname = "list"
for i,p in enumerate(portlist1):
j = len(p.getregisters())
vars()[lname+str(i)] = [(p.getname(),p.getsize()), j]
print list0
print list1
print list2

Related

How to handle operating on items in a list without perfectly even len()?

I'm trying to operate on every 5 items in a list, but can't figure out how to handle the remaining items if they don't divide evenly into 5. Right now I'm using modulo, but I can't shake the feeling it's not quite the right answer. Here's an example...
list = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
i = 0
for o in list:
i += 1
newlist.append(o)
if i % 5 == 0:
for obj in newlist:
function_for(obj)
newlist.clear()
This code will execute function_for() twice, but not a third time to handle the remaining 4 values. If I add an 'else' statement it runs on every execution.
What's the correct way to handle a situation like this?
This way is pretty easy, if you don't mind modifying the list:
mylist = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
while mylist:
function_for( mylist[:5] )
mylist = mylist[5:]
You can also check if the index is equal to the length of the list. (Additionally, it is more idiomatic to use enumerate instead of a counter variable here.)
lst = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
for i, o in enumerate(lst, 1):
newlist.append(o)
if i % 5 == 0 or i == len(lst):
print(newlist)
newlist.clear()

Python code not displaying the list values each in a new line no matter how hard I try

I've written a code which works pretty well, no errors, no problems. But no matter how hard I try to print the list values each in a new line, it still wouldn't work. I've tried sep='\n', and even tried to put the list in a loop to print each value one by one. I still get the result printed all in a row, in one line. This sounds too annoying and I can't figure out why my code is having this strange behavior. Here's my code:
length = int(input())
input_string = [int(y) for y in input().split()]
def lowest(string):
return(min(x for x in string if x is not None))
def none_set(string):
for k in range(length):
if string[k] != None:
if string[k] <=0:
string[k] = None
def counter(string):
nums = 0
for h in range(length):
if string[h] != None:
nums += 1
return nums
cnt = []
for i in range(length):
minimum = lowest(input_string)
none_set(input_string)
cnt.append(counter(input_string))
for j in range(length):
if input_string[j] != None:
input_string[j] -= minimum
result = list(set(cnt))[::-1]
print(result, sep='\n') #Doesn't print the values in new line :/
Sample Input:
6
5 4 4 2 2 8
Expected Output:
6
4
2
1
The Output I Get:
[6, 4, 2, 1]
In case you want to know what exactly my code does, check this link here (No login/signup needed), however, the issue is not really relative to what the goal of my code is, I'd say.
I appreciate in advance, for any tip, solution, or help.
It's because you're printing the whole list.
lst = ['a','b','c']
If I print this list I get ['a','b','c']. To print each item you can use a for loop like so:
lst = ['a','b','c']
for item in lst:
print(item)
#output:
a
b
c
Try this.
for i in result:
print(i)
Try to print like that:
for i in result:
print(i)
Use join() instead of multiple calls to print(). Some will consider it more difficult to read, but it's definitely more efficient even for small lists, and orders of magnitude faster for lists greater than 100 elements.
print("\n".join(map(str, result)))

How do I check every element in an appended text in python

I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.
This is the code I have so far in Python:
i = 0
j = 0
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
count.append(k)
print(count)
Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?
Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.
Any and all help is appreciated.
For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.
You can try this if you want nothing but zero elements.
print [element for element in count if element == 0]
If I understand your question right the answer for your question is like this.
i = 0
j = 0
for i in range (1,10):
# Resetting so that count will not have previous values
count = []
for j in range(1,11):
k = i%j
count.append(k)
# printing all the indexes where the value is '0'
print([index for index, item in enumerate(count) if item == 0])
You know your range of extern loop so you can just write your code in this way :
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
if(i == 9):
count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])

How can I iterate over a list of strings with ints in python?

I'm new to programming with python and programming in general and got stuck wit the following problem:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
How can I make it so the iterating variable is an int so it works the following way?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
The Pythonic way would be with enumerate():
for index, item in enumerate(b):
print index, item
There's also range(len(b)), but you almost always will retrieve item in the loop body, so enumerate() is the better choice most of the time:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
you could always do this:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i

Seriously elusive for loop (racking my brains!)

I've got a loop issue in Python 2.72 that's really frustrating me. Basically the loop is not iterating on the first index j, and I've tried all sorts of ways to fix it with no luck.
def learn(dataSet):
for i in dataSet.getNext():
recall = raw_input("Enter all members of %s you are able to recall >>> (separated by commas) " % (i.getName()))
missed = i.getMembers()
missedString = []
for a in missed:
missedString.append(a.getName())
Here is the loop I can't get to iterate. The first for loop only goes through the first iteration of j in the split string list, then removes it from missedString. I would like for all members of the split-string recall to be removed from missedString.
for j in string.split(recall, ','):
if j in missedString:
missedString.remove(j)
continue
for b in missed:
if b.getName() not in missedString:
missed.remove(b)
print 'You missed %d. ' % (len(missed))
if (len(missed)) > 0:
print 'Maybe a hint or two will help...'
for miss in missed:
remind(miss.getSecs(), i.getName(), missed)
How can I fix the above code?
missedString is a terrible name for a list
Note that you can simplify your code in a few places
missedString = []
for a in missed:
missedString.append(a.getName())
can be replaced by a list comprehension
missedString = [a.getName() for a in missed]
Here you should just use the split method of recall instead of string.split). It looks as though this loop is supposed to be nested inside the for i loop, so I will assume it is (If it's not, you will be using the wrong value of recall with the wrong dataset).
for j in string.split(recall, ','):
if j in missedString:
missedString.remove(j)
continue
It can also be replaced by a list comprehension.
recall_set = set(recall.split(','))
missedString = [j for j in missedString if j not in recall_set]
This will not work properly if eg. the user enters extra spaces in the input, so it's a good idea to strip() those elements
recall_set = set(s.strip() for s in recall.split(','))
missedString = [j for j in missedString if j not in recall_set]
This loop has a serious problem. In general it's not a good idea to remove elements from the list you are iterating over. You'll end up skipping over some elements without checking them
for b in missed:
if b.getName() not in missedString:
missed.remove(b)
Maybe a list comprehension can help again
missed = [b for b in missed if b.getName() in missedString]
In this code
for j in string.split(recall, ','):
if j in missedString:
missedString.remove(j)
continue
try adding an
else:
print 'Didn't remove "%s"' % j
(And get rid of the continue. It's not serving any purpose).
You probably are missing some whitespace from your split. If that's the case, add a j = j.strip() or use re.split(r'\s*,\s*', recall) in place of string.split(recall, ',').

Categories