Is it possible to split the elements of a list? - python

>>> a = bpy.context.selected_objects
>>> a[:2]
[bpy.data.objects['Sphere.001'], bpy.data.objects['Sphere.010']]
>>>
Two list results.
what i need is
It is to move the number after Sphere to notepad.
I do not know.
001 and 010
thank you.

Is this what you want?
for a in bpy.context.selected_objects:
print(a.name.split(".")[-1])
In Blender, you can just split the object's name on the '.' and take the last element in the resulting list. That should print out all those numbers that you want to copy.

#Matti is probably giving you good information on Blender, and the loop will work, but the most direct route to the general case of getting a modified version of each item in a list is by using a list comprehension.
x = ["Sphere.001", "Sphere.010"]
print([y.split(".")[-1] for y in x])

Related

with just four element getting the Memory error in python

I have been getting the memory error but unable to understand the reason behind that. Below is the code. Using the list and appending just two more elements in the list.
mylist = ['phonon', 'communication']
for i in mylist:
mylist.append(i.upper())
print(mylist)
It will be really very helpful if anyone can help me with that.
for i in mylist:
mylist.append(i.upper())
is basically appending to your list while iterating on it. So the iteration never ends.
You want to do:
mylist += [i.upper() for i in mylist]
in that last case, the right-hand expression is computed from a non-modified mylist, then its elements are appended to the existing mylist.
note that the above is equivalent to
mylist.extend([i.upper() for i in mylist])
or
mylist.extend(list(map(str.upper,mylist)))
note that for both snippets above it is necessary to convert to list, or you get the same memory error if the inside is lazily evaluated. The last snippet is probably the fastest because it doesn't use any python loops at all, map, and no lambda
For all 3 snippets the result is:
['phonon', 'communication', 'PHONON', 'COMMUNICATION']
I would add your edited elements to a new list:
uppers = []
for i in mylist:
uppers.append(i.upper())
print(uppers)
Building off Jean's answer:
mylist.extend(i.upper() for i in mylist)
Should give you the desired result.

Assitance in List Value Extractions

what I need right now is to extract a specific file
example:
List = [1,2,3,4,5,6]
print(List[1:2])
Output being [2]
what I need is exactly 2, and not [2]
To python in general, anything will help thanks
In [1]: List = [1,2,3,4,5,6]
In [2]: print(List[1])
2
When you are slicing an array OR list, it means you giving a range of index like [1:5] so, it must return a list. Better you can use single index of array OR list. Then it will return single instance.
Well the easiest way to do this is to just print the value of what you want. I.E:
list = [1,2,3,4,5,6,7,8,9]
print(list[1])
This will print out 2. I am confused on why you are looking in a range of the list which will output another list hence why you are getting [2]. I recommend going back and reading up on lists and what you can do to them in the python tutorials. Youtube might be a great help if your more visual as well. Best of luck
P.S. Remember that lists are 0 based and start at 0. Thus to get 2 in this list, you need to print out the 1 spot which is really the second spot in the list. 0 = 1, 1 = 2, 2 = 3, etc if you look at the list I created.

python list modification to list of lists

I am trying to learn python (just finished Learn Python the Hard Way book!), but I seem to be struggling a bit with lists. Specifically speaking, I have a list like so:
x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]
I would like to operate on this above list, so that it returns a list (somehow!) like so:
y = [ ["/1.ext", "/2.ext"], ["/1.ext", "/2.ext", "/3.ext, "/4.ext"], ["/1.ext", "/2.ext", "/3.ext", "/4.ext", "/5.ext"], ["/1.ext"] ]
So, essentially, each element in x is now turned to a list of lists. I could probably loop over x, store all the sequence lists in another list and then merge then together - but it just seems like there must be a better way to do it.
Would be grateful if someone could point me in the right direction to solve this problem.
EDIT (taking into account Martijn's comments):
Specifically, I want to generate the intermediary filenames in a sequence, ending at the number for each x list element
You can do it as follows:
x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]
print [['/{}.ext'.format(j) for j in range(1,int(i[1])+1)] for i in x]
[OUTPUT]
[['/1.ext', '/2.ext'], ['/1.ext', '/2.ext', '/3.ext', '/4.ext'], ['/1.ext', '/2.ext', '/3.ext', '/4.ext', '/5.ext'], ['/1.ext']]
This only works for digits upto 9. I'll post update for more general solutions
HERE is the more general solution. Works for any numbers:
import re
x = ["/2.ext", "/4.ext", "/5.ext", "/1.ext"]
print [['/{}.ext'.format(j) for j in range(1,int(re.search(r'\d+',i).group(0))+1)] for i in x]

How do replace a list with another list in python?

I am making a hangman game and I want to be able to replace the list of original words with a list of new words typed in by the user. At the minute my code is this:
gamewords[:] = newgamewords[:]
But this does not seem to work...
The original list is this:
gamewords= ['blue','violet','red','orange','fuchsia','cyan','magenta','azure','black','turquoise','pink','scarlet']
A word is then chosen for the list randomly
word=gamewords[random.randint(0,len(gamewords)-1)]
i want to change it so that the word is chosen from the new list, how do i do this?
You probably meant to do this:
gamewords = newgamewords[:] # i.e. copy newgamewords
Another alternative would be
gamewords = list(newgamewords)
I find the latter more readable.
Note that when you 'copy' a list like both of these approaches do, changes to the new copied list will not effect the original. If you simply assigned newgamewords to gamewords (i.e. gamewords = newgamewords), then changes to gamewords would effect newgamewords.
Relevant Documentation
list
I'm not sure what you exactly want. There are two options:
gamewords = newgamewords[:]
gamewords = newgamewords
The difference is that the first option copies the elements of newgamewords and assigns it to gamewords. The second option just assigns a reference of newgamewords to gamewords. Using the second version, you would change the original newgamewords-list if you changed gamewords.
Because you didn't give more of your source code I can't decide which will work properly for you, you have to figure it out yourself.
The obvious choice of functions to use to select one, or a set number of items randomly from a larger list would be random.choice() or random.choices().
>>> gamewords= ['blue','violet','red','orange','fuchsia','cyan','magenta','azure','black','turquoise','pink','scarlet']
>>> random.choice(gamewords)
'turquoise'
>>> random.choice(gamewords)
'orange'
>>> random.choice(gamewords)
'cyan'
>>> random.choices(gamewords, k=3)
['fuchsia', 'orange', 'red']
>>> random.choices(gamewords, k=2)
['turquoise', 'black']
>>>
Not sure if you were able to find the answer to this but I had a similar issue and I resolved it using this method:
for x, y in zip(original_col, np.arange(0, len(original_col), 1)):
df['Term Ldesc'] = df['Term Ldesc'].replace(x, y)
Hope this helps!

how can i append in reverse? python

.append
Function adds elements to the list.
How can I add elements to the list? In reverse? So that index zero is new value, and the old values move up in index?
What append does
[a,b,c,d,e]
what I would like.
[e,d,c,b,a]
Thank you very much.
Suppose you have a list a, a = [1, 2, 3]
Now suppose you wonder what kinds of things you can do to that list:
dir(a)
Hmmmm... wonder what this insert thingy does...
help(a.insert)
Insert object before index, you say? Why, that sounds a lot like what I want to do! If I want to insert something at the beginning of the list, that would be before index 0. What object do I want to insert? Let's try 7...
a.insert(0, 7)
print a
Well, look at that 7 right at the front of the list!
TL;DR: dir() will let you see what's available, help() will show you how it works, and then you can play around with it and see what it does, or Google up some documentation since you now know what the feature you want is called.
It would be more efficient to use a deque(double-ended queue) for this. Inserting at index 0 is extremely costly in lists since each element must be shifted over which requires O(N) running time, in a deque the same operation is O(1).
>>> from collections import deque
>>> x = deque()
>>> x.appendleft('a')
>>> x.appendleft('b')
>>> x
deque(['b', 'a'])
Use somelist.insert(0, item) to place item at the beginning of somelist, shifting all other elements down. Note that for large lists this is a very expensive operation. Consider using deque instead if you will be adding items to or removing items from both ends of the sequence.
Using Python's list insert command with 0 for the position value will insert the value at the head of the list, thus inserting in reverse order:
your_list.insert(0, new_item)
You can do
your_list=['New item!!']+your_list
But the insert method works as well.
lst=["a","b","c","d","e","f"]
lst_rev=[]
lst_rev.append(lst[::-1])
print(lst_rev)
Here's an example of how to add elements in a list in reverse order:
liste1 = [1,2,3,4,5]
liste2 = list()
for i in liste1:
liste2.insert(0,i)
Use the following (assuming x is what you want to prepend):
your_list = [x] + your_list
or:
your_list.insert(0, x)

Categories

Resources