簡體   English   中英

如何將包含多個數字的單個字符串列表拆分為分隔整數列表?

[英]How do I split a list of a single string containing multiple numbers into a list of separated integers?

對不起,我是一個完全的初學者,我在谷歌上找不到很多信息。

對於我的作業,我需要讀取我在文件中生成的內容,並且只有 output 大於 20 但小於 50 的值。我生成了文件,當我讀取文件並打印所有數字的內容時在列表中顯示為單個字符串值:

['11,24,62,59,1,28,61,5,54,38,31']

我已經刪除了逗號所以它出現了

['11 24 62 59 1 28 61 5 54 38 31']

我一直在四處尋找,但找不到適合我的確切問題的東西。

這是我的代碼:

import os

file_path = ("/Users/elian/Desktop/School/Scripting/Week 5/")
os.chdir(file_path)
file_name = ("Lab5.txt")

with open(file_name, "r+") as file:
    contents = file.readlines() # Reads the contents of the file, outputs as a list.
    print(type(contents)) # class 'list'
    contents = ' '.join(str(contents).split(',')) # Removes commas
    print(type(contents)) # class 'str' 

我試過使用 split() 但它似乎只會讓一切變得更糟。

編輯:

這是此文件正在讀取的數字生成器的源代碼:

import os
import random
# Set the file name
file_name = input("Please input your desired file name: ")
# Change the working directory
file_path = input("Please input the file path where this file is to be saved in: ") 
os.chdir(file_path)
# Asks the user how many numbers they would like to generate. 
num_of_values = int(input("How many random numbers would you like generated: "))
with open(file_name, "w") as file:
    for i in range(1, num_of_values + 1):
        random_raw=random.randrange(0,100)
        random_final=int(random_raw)
        file.write
        # convert to a string for the file write
        num_string=str(random_final)
        print(i)
        if i < num_of_values:
            num_string= num_string + ","            
        file.write(num_string)

# Close the file - OS can have issues with files that are not closed
file.close()

因為你想找到圓十,你可以使用正則表達式:

l = ['11,24,62,59,1,28,61,5,54,38,31']

import re

out = ','.join(re.findall(r'\b[234]\d\b', l[0]))

output: '24,28,38,31'

正則表達式:

\b        # word boundary
[234]\d   # 2 digit number starting with 2 or 3 or 4
`b        # word boundary

不包括下限:

l = ['11,20,24,62,59,1,28,61,5,54,38,31']  ## added 20 to the list

import re

','.join(re.findall(r'\b(2[1-9]|[34]\d)\b', l[0]))

output: '24,28,38,31'

正則表達式:

\b        # word boundary
(         # start group
2[1-9]    # 2 digit number starting with 2 and ending in 1-9
|         # OR
[34]\d    # 2 digit number starting with 3 or 4
)         # end group
`b        # word boundary

簡單的pythonic方式:

l = '11,24,62,59,1,28,61,5,54,38,31'
x = [i for i in l.split(",") if 20 < int(i) < 50]
print(x)
# ['24', '28', '38', '31']

假設字符串始終具有以下確切形式:

list_string_in_list = ['11,24,62,59,1,28,61,5,54,38,31'] 
valid_int_list = [int(i) for i in list_string_in_list[0].split(",") if 20 < int(i) < 50]

或者,如果您更喜歡使用循環:

list_string_in_list = ['11,24,62,59,1,28,61,5,54,38,31']
valid_int_list = []
for number in list_string_in_list[0].split(","):
    number_as_int = int(number)
    if 20 < number_as_int < 50:
        valid_int_list.append(number_as_int)

然而,很可能您構建此列表的方式一開始就是錯誤的。 如果您遍歷某些內容並創建此列表,為什么要將它 append 放入列表中的一個長字符串中? 首先使用.append()來填充該列表可能更有意義。

編輯:您正在閱讀的文件中似乎給出了這種格式。 所以只是將其解析為字符串然后拆分是正確的方法。

要更有效地寫入文件:

import random

with open('test.txt', 'w') as file:
    num_list = random.choices(range(100), k=11)
    num_string = ','.join(str(n) for n in num_list)
    file.write(num_string)

或者如果允許使用csv模塊:

import random
import csv

with open('test.txt', 'w', newline='') as file:
    writer = csv.writer(file)
    num_list = random.choices(range(100), k=11)
    writer.writerow(num_list)

讀取文件:

with open('test.txt') as file:
    contents = [int(n) for n in file.read().strip().split(',')]

print(contents)

或者使用csv模塊:

import csv

with open('test.txt', newline='') as file:
    reader = csv.reader(file)
    for line in reader:
        contents = [int(n) for n in line]
        print(contents)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM