简体   繁体   中英

Get the strings of 30 characters from list every time

I have a problem, I only want to get the strings that contains up to 30 characters each time I run it.

import random
test=["test1 up to 30 characters",
      "test2 passing 30 characters easy",
      "test3 up to 30 characters",
      "test4 passing 30 characters easy"]
random.shuffle(test)
if len(test[0])  <= 30:
    print test[0]
elif len(test[0])  >= 30:
    print "Shit"
    print len(test[0])

Edited:****************************************************************************

In the test I will have a variable that will look something like this:

import random
test=["test1 up to "+variable+" characters",
      "test2 passing "+variable+" characters easy",
      "test3 up to "+variable+" characters",
      "test4 passing "+variable+" characters easy"]
random.shuffle(test)
if len(test[0])  <= 30:
    print test[0]
elif len(test[0])  >= 30:
    print "Shit"
    print len(test[0])

That variable will be a mixed number of characters from 5 up to I don't know, let's say 10.

I want the program to select the strings from the list that will contain maximum 30 characters in total. Your solutions just prints out the ones that contains the strings up to 30 characters and that's it. I want it to go back and find the string in the list that will give out a total of 30 characters for every variable each time. I really hope you understand, I am having trouble understanding myself.

Edited *******************************************************************************

Ok, I did this:

import random
test=["test1 up to 30 characters",
      "test2 passing 30 characters easy",
      "test3 up to 30 characters",
      "test4 passing 30 characters easy"]
random.shuffle(test)
print [x for x in test[0:1] if len(x) < 30]

It does what I want, but still gets blanks, like empty []

使用列表理解:

print [x for x in test if len(x) < 30]

You can't have both <= for good and >= for bad, ie you can't have = for both of those. Esentially, the second if should just be an else , since if it's not smaller than or equal to 30, what's left?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM