Python 3:从列表中移除括号

0 投票
2 回答
2751 浏览
提问于 2025-04-18 17:03

我正在尝试从一个列表数组中去掉括号,但没有成功,这是我的代码。

#user input for amount of directories
ask_total_dirs = 100

#begin calculation
num_files = 10 #sets how many files per directory
total_files = int((ask_total_dirs * num_files)) #finds total amount of files
#print (total_files)

phone_num = 50000 #total number of phone numbers per file
total_phone_num = (total_files * phone_num) #total number of phone numbers
#print (total_phone_num)
#end calculation

#begin generator code
def area_code():
    area = [random.randint(1,10) for _ in range(3)] #set for area code
    list_area = str(list(area))
    multiply = str(list_area * total_files) #all amount of area codes needed
    nospace = ( ", ".join( repr(e) for e in multiply ) )
    print (nospace)

area_code()
#end generator code

我得到的输出是……

'[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']', '[', '5', ',', ' ', '2', ',', ' ', '8', ']'

我也试过这段代码,但输出结果还是一样。

nospace = "".join(multiply)

任何帮助都非常感谢

补充说明

顺便说一下,我不得不把这些数组缩短,因为它们太长了,都是我设置的静态变量数字造成的。

当我在nospace之前打印(multiply)时,得到的输出是。

[4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5][4, 4, 5]

2 个回答

0

我使用的是:

list = ["Item 1", "Item 2", "Item 3"]
print("The list contains: ")
for a in range (0, len(list)):
    print("- " + list[a])

这个方法有效,因为它会输出:
- 项目 1
- 项目 3
- 项目 2
我建议使用这个方法来去掉列表周围的括号。
如果你不知道怎么使用 for x in range(),可以去https://www.w3schools.com/python/ref_func_range.asp了解更多信息。

3

只需要这样做:

multiply = multiply.replace('[','').replace(']','')

这段代码会把字符串中的所有括号都去掉。

撰写回答