4Looped:
それは次のように作成されるので、私のリストが正常に機能していない["'carrots, 'tomatoes', 'lettuce'"]
ではなく、['carrots, 'tomatoes', 'lettuce']
私は、テキストファイル持って'carrots, 'tomatoes', 'lettuce'
1行で記述し、これは私が私のリストにそれを書いています方法です。
veggie_list =[]
x = open('veggies.txt','r')
for item in x:
veggie_list.append(item)
Abhiaror:
(あなたは、テキストファイルで複数行を持っていると仮定すると)、これを試してみてください。
veggie_list = []
with open('veg.txt','r') as x:
for item in x:
veggie_list.extend(item.replace("'", "").split(','))
print(veggie_list)
出力:
['carrots', ' tomatoes', ' lettuce']
あなただけのテキストファイルの1行目に興味を持っている場合:
veggie_list = []
with open('veg.txt','r') as x:
veggie_list = x.read().replace("'","").split(',')
print(veggie_list)
使用してPythonでワンライナーリストの内包を:
with open('veg.txt','r') as x:
print([j for i in x for j in i.replace("'","").split(',')])
(最初のコードの場合)説明:
あなたは、まずあなたが読んだライン(から単一引用符を削除する必要がある"'carrots', 'tomatoes', 'lettuce'"
ファイルから)。あなたは使用することができます置き換える()のメソッドstr
オブジェクトを。このメソッドは、変更された文字列のコピーを返し、それが元の文字列を変更しません。
その後、あなたはSTRとままにしておく必要があり"carrots, tomatoes, lettuce"
。今、私が使用しているスプリット()使用して、個々の文字列に文字列全体を分割する方法","
区切り文字としてです。
このメソッドは、リストを返します['carrots', ' tomatoes', ' lettuce']
。