Python 将列表转换为小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17329113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert list to lower-case
提问by goldisfine
I'm trying to get this column of words in input.txt:
我试图在 input.txt 中获取这列单词:
Suzuki music
Chinese music
Conservatory
Blue grass
Rock n roll
Rhythm
Composition
Contra
Instruments
into this format:
变成这种格式:
"suzuki music", "chinese music", "conservatory music", "blue grass", "rock n roll", "rhythm"...
This code:
这段代码:
with open ('artsplus_stuff.txt', 'r') as f:
list.append(", ".join(['%s' % row for row in f.read().splitlines()]))
for item in list:
item.lower()
print list
returns a list, but the first letters are capitalized.
返回一个列表,但首字母大写。
['Suzuki music, Chinese music, Conservatory, Blue grass, Rock n roll, Rhythm, Composition, Contra, Instruments ']
['铃木音乐,中国音乐,音乐学院,蓝草,摇滚乐,节奏,作曲,Contra,乐器']
How do I get all the items lower-cased?
如何让所有项目都小写?
Thanks!
谢谢!
Answer isn't working on this list:
答案不适用于此列表:
Chess
Guitar
Woodworking
Gardening
Car_restoration
Metalworking
Marksman
Camping
Backpacking_(wilderness)
Hunting
Fishing
Whittling
Geocaching
Sports
Model_Building
Leatherworking
Bowling
Archery
Hiking
Connoisseur
Photography
Pool_(cue_sports)
Mountaineering
Cooking
Blacksmith
Aviator
Magic_(illusion)
Foreign_language
Card_game
Blog
Paintball
Fencing
Brewing
Amateur_Astronomy
Genealogy
Adventure_racing
Knitting
Computer_Programming
Amateur_radio
Audiophile
Baking
Bboying
Baton_twirling
Chainmail
Constructed_language
Coloring
Crocheting
Creative_writing
Drawing
Fantasy_Football
Fishkeeping
Home_automation
Home_Movies
Jewelry
Knapping
Lapidary_club
Locksport
Musical_Instruments
Painting
RC_cars
Scrapbooking
Sculpting
Sewing
Singing
Writing
Air_sports
Boardsport
Backpacking
Bonsai
Canoeing
Cycling
Driving
Freerunning
Jogging
Kayaking
Motor_sports
Mountain_biking
Machining
Parkour
Rock_climbing
Running
Sailing
Sand_castle
Sculling
Rowing_(sport)
Human_swimming
Tai_Chi
Vehicle_restoration
Water_sports
Antiques
Coin_collecting
Element_collecting
Stamp_collecting
Vintage_car
Vintage_clothing
Record_Collecting
Antiquities
Car_audio
Fossil_collecting
Insect_collecting
Leaf
Metal_detectorist
Mineral_collecting
Petal
Rock_(geology)
Seaglass
Seashell
Boxing
Combination_puzzle
Contract_Bridge
Cue_sports
Darts
Table_football
Team_Handball
Airsoft
American_football
Association_football
Auto_racing
Badminton
Climbing
Cricket
Disc_golf
Figure_skating
Footbag
Kart_racing
Plank_(exercise)
Racquetball
Rugby_league
Table_tennis
Microscopy
Reading_(process)
Shortwave_listening
Videophile
Aircraft_spotting
Amateur_geology
Birdwatching
Bus_spotting
Gongoozler
Meteorology
Travel
Board_game
Airbrush
Advocacy
Acting
model_aircraft
Pets
Aquarium
Astrology
Astronomy
Backgammon
Base_Jumping
Sun_tanning
Beachcombing
Beadwork
Beatboxing
Campanology
Belly_dance
cycle_Polo
Bicycle_motocross
Boating
Boomerang
Volunteering
Carpentry
Butterfly_Watching
Button_Collecting
Cake_Decorating
Calligraphy
Candle
Cartoonist
Casino
Cave_Diving
Ceramic
Church
Cigar_Smoking
Cloud_Watching
Antique
Hat
album
Gramophone_record
trading_card
Musical_composition
Worldbuilding
Cosplay
Craft
Cross-Stitch
Crossword_Puzzle
Diecast
Digital_Photography
Dodgeball
Doll
Dominoes
Dumpster_Diving
restaurant
education
Electronics
Embroidery
Entertainment
physical_exercise
Falconry
List_of_fastest_production_cars
Felt
Poi_(performance_art)
Floorball
Floristry
Fly_Tying
off-roading
ultimate_(sport)
Game
Garage_sale
Ghost_Hunting
Glowsticking
Gunsmith
Gyotaku
Handwriting
Hang_gliding
Herping
HomeBrewing
Home_Repair
Home_Theater
Hot_air_ballooning
Hula_Hoop
Ice_skating
Impersonator
Internet
Invention
Jewellery
Jigsaw_Puzzle
Juggling
diary
skipping_rope
amateur_Chemistry
Kite
snowkiting
knot
Laser
Lawn_Dart
poker
Leather_crafting
Lego
Macramé
Model_Car
Matchstick_Model
Meditation
Metal_Detector
Rail_transport_modelling
Model_Rocket
ship_model
scale_model
Motorcycle
Needlepoint
Origami
Papermaking
Papier-maché
Parachuting
Paragliding
Pinochle
Pipe_Smoking
Pottery
Powerbocking
Demonstration_(people)
Puppetry
Pyrotechnics
Quilting
pigeon_racing
Rafting
Railfan
Rapping
remote_control
Relaxation
Renaissance_Fair
Renting_movies
Robotics
Rock_Balancing
Role-playing
sand_art_and_play
Scuba_Diving
Self-Defense
Skeet_Shooting
Skiing
Shopping
chtheitroad
Skateboarding
Sketch_(drawing)
SlackLining
Sleep
Slingshot
Slot_Car_Racing
Snorkeling
Soap
Rubik's_Cube
caving
Family
Storm_Chasing
Storytelling
String_Figure
Surf_Fishing
Survival_skills
Tatting
Taxidermy
Tea_Tasting
Tesla_Coil
Tetris
Textile
stone_Rubbing
Antique_tool
Toy
Treasure_Hunting
Trekkie
tutoring
Urban_Exploration
Video_Game
Violin
Volunteer
Walking
Weightlifting
Windsurfing
WineMaking
Wrestling
Zip-line
traveling
error: list.append(", ".join(['"%s"' % row for row in f.read().splitlines()])) TypeError: descriptor 'append' requires a 'list' object but received a 'str' logout
错误:list.append(", ".join(['"%s"' % row for row in f.read().splitlines()])) 类型错误:描述符 'append' 需要一个 'list' 对象,但已收到'str' 注销
采纳答案by Brien
Instead of
代替
for item in list:
item.lower()
change the name of the variable list
to l
or whatever you like that isn'ta reserved word in Python and use the following line, obviously substituting whatever you name the list for l
.
将变量的名称更改list
为l
或任何您喜欢的不是Python 中的保留字的名称并使用以下行,显然将您命名为l
.
l = [item.lower() for item in l]
The lower
method returns a copy of the string in all lowercase letters. Once a string has been created, nothing can modify its contents, so you need to create a new string with what you want in it.
该lower
方法返回所有小写字母的字符串副本。一旦创建了字符串,就无法修改其内容,因此您需要创建一个包含您想要的内容的新字符串。
回答by NPE
Here is how it can be done:
这是如何做到的:
In [6]: l = ['Suzuki music', 'Chinese music', 'Conservatory', 'Blue grass']
In [7]: map(str.lower, l)
Out[7]: ['suzuki music', 'chinese music', 'conservatory', 'blue grass']
One of the reasons your code doesn't behave as expected is that item.lower()
doesn't modify the string (in Python, strings are immutable). Instead, it returnsthe lowercase version of the string, which your code then disregards.
您的代码未按预期运行的原因之一是item.lower()
不修改字符串(在 Python 中,字符串是不可变的)。相反,它返回字符串的小写版本,然后您的代码将忽略它。
回答by Jim Dennis
Easiest might be a list comprehension:
最简单的可能是列表理解:
with open('./input.txt', 'r') as f:
results = [ line.strip().lower() for line in f if line]
... I'm assuming you're willing to strip all leading and trailing whitespace from each line; though you could use just .rstrip()
or even .rstrip('\n')
to be more specific in that. (One would preserve any whitespace on the left of each line, and the other would strip onlythe newlines from the ends of the lines.
...我假设您愿意从每一行中去除所有前导和尾随空格;尽管您可以使用 just.rstrip()
甚至.rstrip('\n')
更具体的方式。(一个将保留每行左侧的任何空白,另一个将仅从行尾去除换行符。
Also this will filter out any blank lines, including the terminal empty line which is almost always found at the end of a text file. (This code will work even with the rare text file that doesn't end with a newline).
这也将过滤掉任何空行,包括几乎总是在文本文件末尾找到的终端空行。(此代码甚至适用于不以换行符结尾的稀有文本文件)。
回答by user1941407
You can use method str.lower().
您可以使用方法 str.lower()。
回答by c0ff3m4kr
For those who like timing tests
对于喜欢计时测试的人
In [1]: %timeit [c.lower() for c in l]
1000000 loops, best of 3: 866 ns per loop
In [2]: %timeit map(str.lower, l)
1000000 loops, best of 3: 1.01 μs per loop
In [3]: %timeit map(lambda x:x.lower(), l)
1000000 loops, best of 3: 1.41 μs per loop
回答by Agent86
In Python strings are immutable. What in Sam Hill does that mean. It means that strings can't be changed. However they can be replaced. An analogy would be to replace your car. Your car is the string variable. You can't change your VW Bug into a Lexus but you can replace it by buying a Lexus. But I don't want two cars! I want the VW Bug replaced and gone leaving only my darling. In other words. I would rather not add another variable to my Python script. But that's just me.
在 Python 中,字符串是不可变的。山姆希尔是什么意思。这意味着不能更改字符串。但是它们可以被替换。一个类比是更换你的汽车。你的车是字符串变量。你不能把你的大众 Bug 改成雷克萨斯,但你可以通过购买雷克萨斯来更换它。但我不要两辆车!我想要更换大众 Bug 并离开,只留下我的宝贝。换句话说。我宁愿不向我的 Python 脚本添加另一个变量。但这只是我。
And I have driven a Bug. It was fun!
而且我已经驾驶了一个错误。好玩!
myList = ["Suzuki music", "Chinese music", "Conservatory music", "Blue grass", "Rock n roll", "Rhythm"]
for i in range(0, len(myList)):
myList[i] = myList[i].lower()
for item in myList:
print item
回答by Viraj Wadate
Simply we can convert list into small latter do this.
简单地我们可以将列表转换为小的后者来做到这一点。
>>> words = ["PYTHON", "PROGRAMMING"]
>>> type((words))
>>> for i in words:
print(i.lower())
output:
输出:
python programming
回答by parabolt
This is another method:
这是另一种方法:
my_list = ['John', 'michael', 'Robert', 'James']
new_list = []
for name in my_list:
new_list.append(name.lower())
print(new_list)