2016-11-09 62 views
-1

讓我們假設我有一個表,如下所示:如何使用逗號在Python中合併列表中的2個元素?

['a', '256','c','d'] 

我的輸出應該

['a','256,c','d'] 

我會更喜歡它修改現有列表直接,而不是創建一個新的列表。

+0

肯定的:L = [ 'A', 'B', 'C'] 爲指數,產品在枚舉(L): \t L [0] = L [0] + L [1] + L [2] \t print L –

+0

編輯您的問題並將該代碼放在那裏,並確保它使用格式化工具進行格式化。此外,解釋爲什麼你的代碼不按照你認爲應該的方式工作。 – idjaw

+0

你在找什麼算法?你做了什麼嘗試?實際上,這可以通過'mylist [:] = ['a','256,c','d']'來回答。 – TigerhawkT3

回答

0

嘗試此

列表= [ '一個', '256', 'C', 'd']

列表[1] = 「」。加入(項目爲項目在名單[1:3]) 希望這是你想要什麼

0

如果你想合併的第二和第三元素試試這個

lst = ['a', '256', 'c', 'd'] 

lst[1] += ',' + lst[2] 
del(lst[2]) 
0

基本上我想提取泰坦尼克號數據集合W沒有使用熊貓這是我們大學給出的任務。泰坦尼克號數據集鏈接如下: https://vincentarelbundock.github.io/Rdatasets/datasets.html

我已經寫這將在下面給出的完整的解決方案:

# isReal function will check whether the given string txt is a floating point number or not. and returns true if it is, and false otherwise. 
def isReal(txt): 
    try: 
     float(txt) 
     return True 
    except ValueError: 
     return False 
# myload is a function that will load the dataset with the given file_name and strips all the unwanted characters like '"','\r','\n',and splits with ',' being the delimiter and this is done with the help of split function then it puts each word in a line in the data set into a list and this list is appended into another list (basically creating list of lists) before this we insert ',' as an element in the list and then use the join function to merge the names of the passengers as a single element in the list and then finally we convert each of the integer element which are string type into integer and same way floats and replace them in the list which finishes the job. Finally we pop the first list from the list of lists. 
def myload(file_name): 
    L=[] 
    with open('train.csv') as f: 
     for line in f: 
      line=line.rstrip('\r\n') 
      l=[element.strip('"') for element in line.split(',')] 
      l.insert(4,',') 
      L.append(l) 

    for l in L: 
     l[3:6]=[''.join(l[3:6])] 
    for l in L: 
     for index, elem in enumerate(l): 
      if l[index].isdigit() == True: 
       l[index]=int(l[index]) 
      else: 
       if isReal(l[index]) == True: 
        l[index]=float(l[index]) 
    L.pop(0)     
    return L 
Li=[] 
nb=input('enter the number of lines u want to display:') 
nb=int(nb) 
i=0 
Li = myload('train.csv') 
while i < nb: 
    print(Li[i]) 
    i+=1 
相關問題