我有一个大约20个名字的列表,我想把它们放进一个数组中。

2024-06-09 15:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是列表:

Annie the Afgan Hound
Bertie the Boxer
Betty the Borzoi
Charlie the Chihuahua
Chaz the Cocker Spaniel
Donald the Dalmatian
Dottie the Doberman
Fern the Fox Terrier
Frank the French Bulldog
George the Great Dane
Gertie the Greyhound
Harry the Harrier
Ian the Irish Wolfhound
Juno the Jack Russell
Keith the Kerry Blue
Larry the Labrador
Marge the Maltese
Max the Mutt
Nutty the Newfoundland
Olive the Old English Sheepdog
Peter the Pug
Poppy the Pekingese
Rosie the Rottweiler
Ruby the Retriever
Sam the Springer Spaniel
Sukie the Saluki
Vernon the Vizsla
Whilma the West Highland Terrier
William the Whippet
Yolande the Yorkshire Terrier

我想得到这个:

array1 = ["Annie the afghan hound","etc"]

有人能帮忙吗


Tags: the列表houndcharliebettyanniechazboxer
1条回答
网友
1楼 · 发布于 2024-06-09 15:10:12

如果您需要对每一行进行一些操作,那么您可以这样循环

file = open(“testfile.txt”, “r”) 
contents= []
for line in file: 
    print line
    contents.append(line)
file.close()

在这里,你可以读取文本文件,并将它们存储在列表中,就像这样,你需要与我们分享更多的细节,就像这是你正在阅读的文本文件。您试图解决的问题等,但欢迎使用Stackoverflow:)

正如Roganjosh所建议的那样,只需两行代码就可以读取文件的内容并创建一个列表

fh = open(“hello.txt”, “r”) 
print fh.readlines() #print or store as list or array
fh.close()

fh.readlines()返回您想要的列表

look for examples here please

使用with处理文件打开是最佳实践,它有助于处理操作中的异常处理。如果使用with,它还可以关闭自动打开的文件

with open(“hello.txt”) as f: 
    data = f.readlines() 

相关问题 更多 >